简体   繁体   中英

python: Convert from PNG to JPG without saving file to disk using PIL

In my program I need to convert a .png file to .jpg file but I don't want to save the file to disk. Currently I use

>>> from PIL import Imag
>>> ima=Image.open("img.png")
>>> ima.save("ima.jpg")

But this saves file to disk. I dont want to save this to disk but have it converted to .jpg as an object. How can I do it?

You can do what you are trying using BytesIO from io:

from io import BytesIO

def convertToJpeg(im):
    with BytesIO() as f:
        im.save(f, format='JPEG')
        return f.getvalue()

Improving answer by Ivaylo:

from PIL import Image
from io import BytesIO

ima=Image.open("img.png")

with BytesIO() as f:
   ima.save(f, format='JPEG')
   f.seek(0)
   ima_jpg = Image.open(f)

This way, ima_jpg is an Image object.

To use the ima_jpg object in @tuxmanification's approach outside of the with statement, use Image.load() :

from PIL import Image
from io import BytesIO

ima=Image.open("img.png")

with BytesIO() as f:
   ima.save(f, format='JPEG')
   f.seek(0)
   ima_jpg = Image.open(f)
   ima_jpg.load()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM