python:将PNG转换为JPG,而无需使用PIL将文件保存到磁盘



在我的程序中,我需要将.png文件转换为.jpg文件,但我不想将文件保存到磁盘。目前我使用

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

但是这会将文件保存到磁盘。我不想把这个保存到磁盘上,但把它转换成.jpg作为一个对象。我该怎么做呢?

你可以使用BytesIO from io:

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

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)

这样,ima_jpg就是一个Image对象

要在with语句之外使用@tuxmanification方法中的ima_jpg对象,请使用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()

最新更新