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

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

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.