How to recover EXIF ​​data after image resizing using PIL?

This question has been asked before , but it was answered several years ago, and the answer relates to a broken link and probably not the best method anymore.

pyxiv2 looks like it will complete the task, but it has many dependencies for a seemingly simple task.

I would also like to know which values ​​will no longer be valid for the resized image. Width and height are obvious.

+3
source share
1 answer

Just in case, someone would like to use piexiv2, here is the solution: resizing the image using the PIL library, EXIF ​​data copied from pyexiv2, and the sizes of the EXIF ​​fields of the image are set to a new size.

import pyexiv2
import tempfile
from PIL import Image


def resize_image(source_path, dest_path, size):
    # resize image
    image = Image.open(source_path)
    image.thumbnail(size, Image.ANTIALIAS)
    image.save(dest_path, "JPEG")

    # copy EXIF data
    source_image = pyexiv2.Image(source_path)
    source_image.readMetadata()
    dest_image = pyexiv2.Image(dest_path)
    dest_image.readMetadata()
    source_image.copyMetadataTo(dest_image)

    # set EXIF image size info to resized size
    dest_image["Exif.Photo.PixelXDimension"] = image.size[0]
    dest_image["Exif.Photo.PixelYDimension"] = image.size[1]
    dest_image.writeMetadata()

# resizing local file
resize_image("41965749.jpg", "resized.jpg", (600,400))
+3
source

Source: https://habr.com/ru/post/1771614/


All Articles