pythonpython-imaging-librarypyexiv2

how maintain exif data of images resizes using PIL


when I try to resize(thumbnail) an image using PIL , it destroys the exif data associated with the image, How can I save it.

I resize the image and upload it to the cloud as image buffer.

file_path = '...'
file_name = '...'
im = Image.open( file_path )
size =(512,521)
im.thumbnail( size, Image.ANTIALIAS)
thumbnail_buf_string = StringIO.StringIO()
file_save_extension = 'JPEG'
im.save(thumbnail_buf_string, format=file_save_extension)
upload_to_cloud('512_' + file_name , thumbnail_buf_string.getvalue())

The resized image has no exif data.


Solution

  • Note: I haven't done this myself yet, but to my knowledge, PIL only allows to read exif tags but cannot write them. You will probably need gexiv2 or pyexiv2 to write the tags to your thumbnails.

    UPDATE: I got curious and tried it myself :D If i got you right, you just want to copy the metadata without further modifications.

    This is still crude but seems to work:

    import os
    import Image
    import pyexiv2
    
    fp = '/home/klaus/workspace'
    fn = 'img_2380.jpg'
    
    full_path = os.path.join(fp, fn)
    print full_path
    
    im = Image.open(full_path)
    size = 512, 512
    im.thumbnail(size, Image.ANTIALIAS)
    im.save('bla.jpg', 'JPEG')
    
    oldmeta = pyexiv2.ImageMetadata(full_path)
    oldmeta.read()
    # read metadata of the original file
    
    newmeta = pyexiv2.ImageMetadata('bla.jpg')
    newmeta.read()
    # read metadata of the new file
    # yes, there aren't any, but this is crucial!
    # you need this class as the target for copying!
    
    oldmeta.copy(newmeta)
    
    newmeta.write()
    # don't forget to write the data to the new file
    

    BTW: Thanks for the interesting question!