the writings of

Using PIL to edit an image while maintaining the image's quality

February 9, 2011

Manipulating an image with Python and the Python Imaging Library (PIL) while maintaining the image's quality.

Here's something that was bugging me for a while. It was one of those things that was justannoying enough to make me cringe whenever I saw the result but never important enough to fix.

At any rate, for some time I have been working on a project at my day-job where some simple server-side image manipulation was required. It's a Django project, so I've been using Python's PIL. All I was doing was some resizing and cropping.

When I first started using PIL, I noticed that I was getting some significant grainyness when saving an image. After a little poking around, I found that during image resizing, one can use an anti-aliasing filter.

import Image
img ="path/to/image.jpg")
img = img.resize((100,100), Image.ANTIALIAS)"path/to/new_image.jpg")

This somewhat cleared up the image quality issues I was having. It still wasn't great, mind you, but it was generally "good enough" and at the time, I needed to move on.

Months went by of looking at those resized images and being just ever-so-slightly annoyed; not enough to do anyhting about it but just enough to subconsciously cringe a little each time I saw one. Recently, I was revisiting that part of the project and decided it would be a good time to try to figure out how to maintain better image quality when using the PIL.

What I found (and what doesn't seem to be documented in the PIL's Image docs) is that one can pass a "quality" argument to the save method.

import Image
img ="path/to/image.jpg")
img = img.resize((100,100), Image.ANTIALIAS)"path/to/new_image.jpg", quality=100)

Left to right: (1)Original image, (2)Raw save using PIL, (3)Save after using ANTIALIAS only, (4)Save using ANTIALIAS and quality setting

This is akin to dealing with the quality setting when saving a JPEG in photoshop. I learned this out after finding Djangosaur, which, by the way, is a damn cool name for a django blog.

Top to bottom, Left to right: (1)Original image, (2)Raw save using PIL, (3)Save after using ANTIALIAS only, (4)Save using ANTIALIAS and quality setting

It's somewhat tough to see the difference between antialias only and antialiased saved at 100 quality in the above examples. It's probably clearer in the picture of me than in the picture of the dog. However, it is a bit grainier, especially in larger images.

blog comments powered by Disqus