Resize image in Python without losing EXIF data

后端 未结 11 2083
野的像风
野的像风 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

    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()
    

提交回复
热议问题