How to do JPEG compression in Python without writing / reading

I would like to work directly with compressed JPEG images. I know that with PIL / Pillow I can compress the image while saving it and then read the compressed image - for example,

from PIL import Image
im1 = Image.open(IMAGE_FILE)
IMAGE_10 = os.path.join('./images/dog10.jpeg')
im1.save(IMAGE_10,"JPEG", quality=10)
im10 = Image.open(IMAGE_10)

but, I would like to do it without extraneous writing and reading. Is there any Python package with a function that will accept image and quality as input and return a jpeg version of this image with the given quality?

+12
source share
2 answers

For file files in memory 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 file photo-quality10.jpg, it should be the same image, but with 10% quality, as when setting JPEG compression.

+11

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

Python3.0 StringIO, StringIO python3

+5

All Articles