Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 916
Vivek Sasidharan Avatar asked Jul 14 '15 14:07

Vivek Sasidharan


People also ask

How do I Pil an image?

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).


2 Answers

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()
like image 93
Ivaylo Strandjev Avatar answered Sep 20 '22 14:09

Ivaylo Strandjev


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.

like image 27
tuxmanification Avatar answered Sep 17 '22 14:09

tuxmanification