How does Python PIL and PILLOW compress pictures?

Natulux picture Natulux · Feb 20, 2014 · Viewed 12.2k times · Source

I wanted to write a program with Python 3.3 in which a frame is added to a picture. I use the PIL package from Python to do that. But the pictures I get are less than a third as big as the original and they loose quite some focus/sharpness/gloss. Where does Python compress/change the picture and how (if possible) can I subdue it?

I could think of some passages, which might be the one compressing.

  1. I load the image with PIL:

    img = Image.open(element)

  2. I create a new picture, which is black:

    newImg = Image.new("RGB",(imgWidthNew,imgHightNew),(0,0,0,0))

  3. I create a pixel map out of my picture and change some:

    pixels = newImg.load()

  4. I paste my picture into the middle of the black one:

    newImg.paste (Image.open(element), (halfFrameWidth, halfFrameHight, imgWidth+halfFrameWidth, imgHight+halfFrameHight))

  5. The new image is beeing saved:

    newImg.save(path,dpi=[300,300])

I load mostly .jpg pictures, but due to some problems I extract .bmp files.

 path = path[:path.rfind(".")] + fileEnding

But this shouldnt be the problem, because I have the same issues without changing the data type. My operating system is Windows7 64BIT and I use Pillow 2.3.0 with Python 3.3.

Thank you for any help.

Answer

unutbu picture unutbu · Feb 20, 2014

When saving as JPEG, you can set the quality parameter to control the amount of compression:

newImg.save(path, 'JPEG', dpi=[300,300], quality=90)

Or, save in a lossless format, such as PNG:

newImg.save(path, 'PNG', dpi=[300,300])