Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform JPEG compression in Python without writing/reading

I'd like to work directly with compressed JPEG images. I know that with PIL/Pillow I can compress an image when I save it, and then read back the compressed image - e.g.

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'd like a way to do this without the extraneous write and read. Is there some Python package with a function that will take an image and quality number as inputs and return a jpeg version of that image with the given quality?

like image 1000
user1245262 Avatar asked Jun 11 '15 04:06

user1245262


People also ask

How do I compress a JPEG in Python?

getsize(image_name) # print the size before compression/resizing print("[*] Size before compression:", get_size_format(image_size)) if new_size_ratio < 1.0: # if resizing ratio is below 1.0, then multiply width & height with this ratio to reduce image size img = img. resize((int(img. size[0] * new_size_ratio), int(img.

How do I compress an image without losing quality in Python?

Those who know a bit of python can install python and use pip install pillow in command prompt(terminal for Linux users) to install pillow fork. Assemble all the files in a folder and keep the file Compress.py in the same folder. Run the python file with python.

What coding is used for JPEG compression?

JPEG is a lossy image compression method. It employs a transform coding method using the DCT (Discrete Cosine Transform). An image is a function of i and j (or conventionally x and y) in the spatial domain.


1 Answers

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.

like image 62
sgammon Avatar answered Sep 28 '22 19:09

sgammon