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?
Image. open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With