Search code examples
pythonimageimage-processingpython-imaging-librarymetadata

I can't seem to keep the extra info in the images after resizing them


I am trying to resize images to a resolution of width 760 pixels and height 580 pixels through a python script. But, the resized images do not contain their original metadata in Image properties >> details tab. All the metadata is lost after the image is resized. I was able to retain the original dpi and preserve the original aspect ratio while resizing. However, I am lost at preserving the metadata. Please help !

def resize_images(input_folder, output_folder, width, height):
    # output folder
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    
    for filename in os.listdir(input_folder):
        if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename)
            with Image.open(input_path) as image:
                # Calculate the aspect ratio
                aspect_ratio = image.width / float(image.height)
                new_height = int(width / aspect_ratio)
                resized_image = image.resize((width, new_height), Image.LANCZOS)
                dpi = image.info.get("dpi", (300, 300))  # Default DPI: 300
                resized_image.save(output_path, dpi=dpi)

I am using PIL library. The above function was able to retain original dpi and aspect ratio of image after resized and it can also change the case of file names from upper to lower case. however, it doesn't retain the metadata in resized images.


Solution

  • Try:

    resized_image.save(output_path, dpi=dpi, exif=image.getexif())