Preserve exif data of image with PIL when resize(create thumbnail)
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 Imageimport piexifimport StringIOfile_path = '/home/me/img/a.JPG'im = Image.open( file_path)# load exif dataexif_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
I read throught some of the source code and found a way to make sure that the exif data is saved with the thumbnail.
When you open a jpg file in PIL, the Image
object has an info
attribute which is a dictionary. One of the keys is called exif
and it has a value which is a byte string - the raw exif data from the image. You can pass this byte string to the save method and it should write the exif data to the new jpg file:
from PIL import Imagesize = (512, 512)im = Image.open('P4072956.jpg')im.thumbnail(size, Image.ANTIALIAS)exif = im.info['exif']im.save('P4072956_thumb.jpg', exif=exif)
To get a human-readable version of the exif data you can do the following:
from PIL import Imagefrom PIL.ExifTags import TAGSim = Image.open('P4072956.jpg')for k, v in im._getexif().items(): print TAGS.get(k, k), v
import pyexiv2from PIL import Imagefile_path = '/home/../img/a.JPG'metadata = pyexiv2.ImageMetadata(file_path)metadata.read()thumb = metadata.exif_thumbnailthumb.set_from_file(file_path)thumb.write_to_file('512_' + "a")thumb.erase()metadata.write()
Now I open the image using (Patch Image Inspector) , I can see the exif data