Python: convert from PNG to JPG without saving the file to disk using PIL

In my program, I need to convert the .png file to a .jpg file, but I do not want to save the file to disk. I am currently using

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

But this saves the file to disk. I do not want to save this to disk, but it will convert to .jpg as an object. How can i do this?

+6
source share
2 answers

You can do what you are trying to use BytesIO from io:

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

Improving Ivaylo's answer:

 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) 

So ima_jpg is an Image object.

+1
source

All Articles