Search code examples
pythonimagecompressionjpegpython-imaging-library

Python PIL (Pillow) resizes my pictures after modifying exif data


i made a small script in Python, which can set the exif data of my old Whatsapp pictures based on their filename.

I use the piexif and the PIL (Pillow) package.

import piexif
from PIL import Image
from collections import defaultdict

img = Image.open(fname)

try:
    exif_dict = piexif.load(img.info["exif"])
except KeyError:
    exif_dict = defaultdict(dict)

exif_dict['Exif'][piexif.ExifIFD.DateTimeOriginal] = exiftime(date)
exif_dict['Exif'][piexif.ExifIFD.DateTimeDigitized] = exiftime(date)

exif_bytes = piexif.dump(exif_dict)
img.save('%s' % fname, "jpeg", exif=exif_bytes)

The exiftime() function is only for formatting the date.

However, the script is setting some exif fields, i don't modify compression or someting like that.

My problem is, that the pictures get much smaller, after running that script. I tested this script with some sample images, e.g. a picture shot with a Nikon D5300 with an resolution of 6000x4000. The original file has about 12Mb, after the script it has only 4Mb.

Does the script cause a quality loss of the picture, or is it just a better compression?


Solution

  • Pillow's .save automatically compresses with a default of 75% quality according to the documentation. You can bump that up to 100% (add quality=100), which will minimize compression and looks like it will skip some compression components completely, but Pillow apparently doesn't have the ability to skip compression altogether. Very few packages do this, and I'm unaware of any in the form of a Python module. Note that the docs say not to raise quality over 95, and I can attest that doing so outputs a BIGGER file.. weird.