Search code examples
pythonalgorithmpngpython-imaging-libraryimage-compression

Scaling down the PNG images is increasing the image size


I am trying to scale down all the images in a folder to 90% of their respective sizes. Wrote this :

from PIL import Image
import sys, csv, os, traceback

path = "C:\Users\Dell\Desktop\Textures\\"
dirs = os.listdir( path )
scalingFactor = .9

def resize():
 for item in dirs:
    print 'item', path+item
    if os.path.isfile(path+item):
        im = Image.open(path+item)
        f, e = os.path.splitext(path+item)
        imResize = im.resize((int(im.size[0]*scalingFactor),int(im.size[1]*scalingFactor)), Image.ANTIALIAS)
        fileName = f.split('\\')[-1]
        imResize.save(path + "/Out/" + fileName + ' resized_' + str(scalingFactor) + ".png" , 'PNG')

However, when I run it, the size of images are actually increasing instead of decreasing (as I expect).

eg. Original Image 885x1130 466KB

enter image description here

Output Image 796x1017 1.44 MB!

enter image description here

I have had a rather similar un-intuitive experience earlier with PNGs while rotating them and got an explanation about it here on Stackoverflow. But I can't convinve myself that this is perhaps the same issue.

Any clues ? and something else I can do to reduce the PNG size ? Am ok with a little loss in quality if required.


Solution

  • You have used Image.ANTIALIAS filter which is a high-quality downsampling filter.

    To reduce the size of the image you can use optimize=True and quality=90 while saving the image. Like -

    imResize.save(path + "/Out/" + fileName + ' resized_' + str(scalingFactor) + ".png" ,optimize=True,quality=90)
    

    The optimize flag will do an extra pass on the image to find a way to reduce it's size as much as possible.

    Now to reduce the size further, you can change the quality value in the save options.

    I prefer quality 85 with optimize because the quality isn't affected much, and the file size is much smaller.

    Hope this helps!


    Just to add to your answer, all the filters are listed here to make a decision about quality vs speed of execution etc.

    https://pillow.readthedocs.io/en/stable/handbook/concepts.html#filters