Update Metadata Comments in a png file in Python

1.3k Views Asked by At

I am trying to update Metadata Comments(Details -> Description -> Comments) in image files(jpg format) for a bunch of images in directory based on a certain criteria. The metadata comments are of string values separated by spaces. Example of a metadata comment - "ABC 123 07-04-21" etc. Please see the picture attached.

enter image description here

I get a bunch of image files and comments in a csv file stored in the same directory as the images. I need to match image file names with the files present in the directory and update the comments from the csv file to the images Metadata Comments(Details -> Description -> Comments).

I tried several things. Was able to find out how to update comments in a jpg file, although works for a single image.

Code snippet to update comments in a single JPG file. Encode is essential to actually see the updated comments in the jpg file.

im = Image.open("20210430.jpg")
exif_dict["0th"][piexif.ImageIFD.XPComment] = "Test comments 12345".encode('utf-16le')
exif_bytes = piexif.dump(exif_dict)
im.save("20210430.jpg.jpg", exif=exif_bytes)

Few things which I tried:

from PIL import Image
import piexif
import pandas as pd
import glob
import os


--dataframe to store list of image file names and comments to update.

df1= pd.read_csv('FinalImageMetaData.csv')

--dataframe which has list of images file names in the directory.

df2=pd.read_csv('ListImage.csv')

merged_inner = pd.merge(left=df2, right=df1, left_on='IMAGE_NAME', right_on='IMAGE_NAME')

#merged_inner[['METADATA']]

images = glob.glob(r"C:.\.\Programs\*.jpg")

for image in images:

     with open(image, 'rb') as file:

        img = Image.open(file)

        exif_dict = piexif.load(img.info["exif"])

        exif_dict["0th"][piexif.ImageIFD.XPComment] = merged_inner[['METADATA']].encode('utf-16le')
        exif_bytes = piexif.dump(exif_dict)

        img.save(file, exif=exif_bytes)
        

Sample Contents of FinalImageMetaData.csv

IMAGE_NAME,METADATA

20210430.jpg,12345 02/27/2021 00:00:00   
20210429.jpg,34567 02/27/2021 00:00:00   
20210428.jpg,90897 02/27/2021 00:00:00   
20210427.jpg,56789 02/27/2021 00:00:00   
20210426.jpg,34567 02/27/2021 00:00:00

Sample Contents of ListImage.csv

IMAGE_NAME

20210430.jpg

20210429.jpg

20210428.jpg

20210427.jpg

20210426.jpg

20210425.jpg

20210424.jpg

20210423.jpg

20210422.jpg

Please share any ideas/code snippets.

0

There are 0 best solutions below