Preserve exif data of image with PIL when resize(create thumbnail)

Jisson picture Jisson · Jun 11, 2013 · Viewed 10.9k times · Source

When I try to resize (thumbnail) an image using PIL, the exif data is lost.

What do I have to do preserve exif data in the thumbnail image? When I searched for the same, got some links but none seem to be working.

from PIL import  Image
import StringIO

file_path = '/home/me/img/a.JPG'
im = Image.open( file_path)
THUMB_SIZES = [(512, 512)]
for thumbnail_size in THUMB_SIZES:
    im.thumbnail( thumbnail_size, Image.ANTIALIAS)
    thumbnail_buf_string = StringIO.StringIO()
    im.save('512_' + "a", "JPEG")

The orginal image has exif data, but image im(512_a.JPEG) doesn't.

Answer

Nguyen Sy Thanh Son picture Nguyen Sy Thanh Son · Nov 24, 2015

In my project, i met the same issue with you. After searching Google, I found piexif library. It help to Pilow save exif data to thumbnails.

You can use the source code below:

from PIL import  Image
import piexif
import StringIO


file_path = '/home/me/img/a.JPG'
im = Image.open( file_path)

# load exif data
exif_dict = piexif.load(im.info["exif"])
exif_bytes = piexif.dump(exif_dict)

THUMB_SIZES = [(512, 512)]
for thumbnail_size in THUMB_SIZES:
    im.thumbnail( thumbnail_size, Image.ANTIALIAS)
    thumbnail_buf_string = StringIO.StringIO()
    # save thumbnail with exif data
    im.save('512_' + "a", "JPEG", exif=exif_bytes)

Note: I am using python 3.4 and ubuntu 14.04