Resize image in Python without losing EXIF data

后端 未结 11 2003
野的像风
野的像风 2020-12-02 19:06

I need to resize jpg images with Python without losing the original image\'s EXIF data (metadata about date taken, camera model etc.). All google searches about python and i

相关标签:
11条回答
  • 2020-12-02 19:28

    It seems @Depado's solution does not work for me, in my scenario the image does not even contain an exif segment.

    pyexiv2 is hard to install on my Mac, instead I use the module pexif https://github.com/bennoleslie/pexif/blob/master/pexif.py. To "add exif segment" to an image does not contain exif info, I added the exif info contained in an image which owns a exif segment

    from pexif import JpegFile
    
    #get exif segment from an image
    jpeg = JpegFile.fromFile(path_with_exif)
    jpeg_exif = jpeg.get_exif()
    
    #import the exif segment above to the image file which does not contain exif segment
    jpeg = JpegFile.fromFile(path_without_exif)
    exif = jpeg.import_exif(jpeg_exif)
    jpeg.writeFile(path_without_exif)
    
    0 讨论(0)
  • 2020-12-02 19:28

    Updated version of Maksym Kozlenko Python3 and py3exiv2 v0.7

    # Resize image and update Exif data
    from PIL import Image
    import pyexiv2
    
    def resize_image(source_path, dest_path, size):
        # resize image
        image = Image.open(source_path)
        # Using thumbnail, then 'size' is MAX width or weight
        # so will retain aspect ratio
        image.thumbnail(size, Image.ANTIALIAS)
        image.save(dest_path, "JPEG")
    
        # copy EXIF data
        source_exif = pyexiv2.ImageMetadata(source_path)
        source_exif.read()
        dest_exif = pyexiv2.ImageMetadata(dest_path)
        dest_exif.read()
        source_exif.copy(dest_exif,exif=True)
    
        # set EXIF image size info to resized size
        dest_exif["Exif.Photo.PixelXDimension"] = image.size[0]
        dest_exif["Exif.Photo.PixelYDimension"] = image.size[1]
        dest_exif.write()
    
    0 讨论(0)
  • 2020-12-02 19:29

    Here's an updated answer as of 2018. piexif is a pure python library that for me installed easily via pip (pip install piexif) and worked beautifully (thank you, maintainers!). https://pypi.org/project/piexif/

    The usage is very simple, a single line will replicate the accepted answer and copy all EXIF tags from the original image to the resized image:

    import piexif
    piexif.transplant("foo.jpg", "foo-resized.jpg")
    

    I haven't tried yet, but it looks like you could also perform modifcations easily by using the load, dump, and insert functions as described in the linked documentation.

    0 讨论(0)
  • 2020-12-02 19:39
    import jpeg
    jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg') 
    

    http://www.emilas.com/jpeg/

    0 讨论(0)
  • 2020-12-02 19:39

    PIL handles EXIF data, doesn't it? Look in PIL.ExifTags.

    0 讨论(0)
提交回复
热议问题