How to perform JPEG compression in Python without writing/reading

For in-memory file-like stuff, you can use StringIO. Take a look:

from io import StringIO # "import StringIO" directly in python2
from PIL import Image
im1 = Image.open(IMAGE_FILE)

# here, we create an empty string buffer    
buffer = StringIO.StringIO()
im1.save(buffer, "JPEG", quality=10)

# ... do something else ...

# write the buffer to a file to make sure it worked
with open("./photo-quality10.jpg", "w") as handle:
    handle.write(buffer.contents())

If you check the photo-quality10.jpg file, it should be the same image, but with 10% quality as the JPEG compression setting.


Using BytesIO

try:
    from cStringIO import StringIO as BytesIO
except ImportError:
    from io import BytesIO

def generate(self, image, format='jpeg'):
    im = self.generate_image(image)
    out = BytesIO()
    im.save(out, format=format,quality=75)
    out.seek(0)
    return out

StringIO is missing in Python3.0, ref to : StringIO in python3