Image Library convert from JPEG to

不羁岁月 提交于 2019-12-21 12:23:29

问题


I'm attempting to convert a JPEG file with, 200 dpi, to a PDF file, however, when I save the file as a PDF I think it's changing the dpi to 72, and thus making the image larger. I had a similar problem when initially trying to scale my JPEG image to a smaller size, and was able to solve that by specifying the dpi when I save the image.

im = Image.open("Image.jpg")

dpi=im.info['dpi']

if im.size == (2592, 1728):
    out = im.resize((1188,792), Image.ANTIALIAS)
elif im.size == (1728,2592):
    out = im.resize((792,1188), Image.ANTIALIAS)

out.save(project, dpi=dpi)

Now when I try to save this JPEG as a PDF, specifying the dpi doesn't seem to make any difference, and I get an image that is larger than my original that looks like it has a lower dpi. Is there a way to mantain a consistent resolution when converting from JPEG to PDF using PIL? Or is there a better way for me to go about doing this?

This is what I have for converting a directory of files from JPEG to PDF:

for infile in listing:

    outfile = destpath + os.path.splitext(infile)[0] + ".pdf"
    current = path + infile

    if infile != outfile:
        im = Image.open(current)
        dpi=im.info['dpi']

        im.save(outfile, "PDF", Quality = 100)

回答1:


In the CHANGES file of PIL 1.1.7 sources one can read:

  • Added resolution save option for PDF files.

    Andreas Kostyrka writes: I've included a patched PdfImagePlugin.py
    based on 1.1.6 as included in Ubuntu, that supports a "resolution"
    save option. Not great, but it makes the PDF saving more useful by
    allowing PDFs that are not exactly 72dpi.

So you should be able to do:

im.save(outfile, "PDF", resolution=100.0)

(seems to work fine on my Ubuntu box).




回答2:


You can use reportlab library.

import sys

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, flowables

__jpgname = str()
def drawPageFrame(canvas, doc):
    width, height = letter
    canvas.saveState()
    canvas.drawImage(
    __jpgname, 0, 0, height, width,
    preserveAspectRatio=True, anchor='c')
    canvas.restoreState()

def jpg2pdf(pdfname):
    width, height = letter

    # To make it landscape, pagesize is reversed
    # You can modify the code to add PDF metadata if you want
    doc = SimpleDocTemplate(pdfname, pagesize=(height, width))
    elem = []

    elem.append(flowables.Macro('canvas.saveState()'))
    elem.append(flowables.Macro('canvas.restoreState()'))

    doc.build(elem, onFirstPage=drawPageFrame)

if __name__ == '__main__':
    if len(sys.argv) < 3:
    print("Usage: python jpg2pdf.py <jpgname> <pdfname>")
    exit(1)
    __jpgname = sys.argv[1]
    jpg2pdf(sys.argv[2])



回答3:


It is important that PIL parameters are lowercase.

im.save(outfile, "PDF", quality = 100)

Quality = 100 ----will not work.




回答4:


Here is a code that convert any file with .jpg or .JPG extension and convert into pdf, and then delete the images that have been converted. Sorry the comments are in french.

import os #necessaire pouvoir supprimer l'image une fois converti et parcourir les fichers dans le dossier
from fpdf import FPDF #necessaire pour convertir les jpg en pdf


for file in os.listdir(): # pour chaque fichiers dans le dossier dans lequel se trouve ce fichier python
if file.endswith(".jpg") or file.endswith(".JPG"): #permet de selectionner les fichers avec l'extension .jpg ou .JPG
    img=os.path.join(file) #convertie le nom du fichier en variable
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.image('%s'%img, 3,3,204 ) # les chiffres permettent de positionner l'image sur le pdf : 3mm de la gauche, 3mm du haut, et 204 mm de la gauche pour la fin de l'image
    img2=img[:-4] #supprime les 4 dernières lettres du nom du ficher, à savoir '.jpg' ou '.JPG'
    pdf.output('%s.pdf'%img2,'F') #convertie en pdf
    os.remove('%s'%img) #supprime les fichier jpg ou JPG



回答5:


You might need to use:

import PIL
import PIL.Image

filename = 'filename'
im = PIL.Image.open(filename)

newfilename = 'path.pdf'
PIL.Image.Image.save(newfilename,outfile, "PDF", resoultion = 100.0)

I'm using windows and I used pip to install PIL. For some reason it switched to PIL.Image.Image




回答6:


A complete example here:

import os
import PIL.Image

def img2pdf(fname):
    filename = fname
    name = filename.split('.')[0]
    im = PIL.Image.open(filename)
    if not os.path.exists('im2pdf_output'):
        os.makedirs('im2pdf_output')
    newfilename = ''.join(['im2pdf_output/',name,'.pdf'])
    PIL.Image.Image.save(im, newfilename, "PDF", resolution = 100.0)
    print("processed successfully: {}".format(newfilename))

files = [f for f in os.listdir('./') if f.endswith('.jpg')]
for fname in files:
    img2pdf(fname)



回答7:


The correct usage of save is:

PIL.Image.Image.save(im, newfilename, "PDF", resolution = 100.0)

example:

path='v:/dev/python/mooc/'
filename = path + '2016_a_milano_001.JPG'
im = PIL.Image.open(filename)
newfilename = path+ 'r.pdf'
PIL.Image.Image.save(im, newfilename, "PDF", resoultion=100.0)


来源:https://stackoverflow.com/questions/12626654/image-library-convert-from-jpeg-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!