Home > AI > Language > Python >

add timestamp to the jpg

Step 1: exifread and heic-to-jpg

Step 2

import glob


# 1 - convert HEIC to jpg
import subprocess
import os

# 2 - read HEIC metadata
import exifread
# import pyheif # notworking

# 3 -  put txt to image
# from PIL import Image, ImageDraw, ImageFont, ImageOps # notworking
import cv2








def convertHEICToJPG(filename):
    # subprocess.run(["heic2jpg -s "+filename+" --keep"])

    # problem: command not found
    # solution: give absolute path for the command since it cannot load the environment
    os.system("/opt/anaconda3/bin/heic2jpg -s "+filename+"  --keep") # command not found


def get_timestamp(filename):
    # Open image file for reading (binary mode)
    f = open(filename, 'rb')

    # Return Exif tags
    tags = exifread.process_file(f)
    time = tags.get('Image DateTime')

    return str(time)


def add_timestamp(filename, timestamp):
    # assert
    if not os.path.isfile(filename):
        print(filename + " doesn't exist")
        return

    # get image information
    img = cv2.imread(filename, cv2.IMREAD_UNCHANGED)

    # font
    font = cv2.FONT_HERSHEY_SIMPLEX
    # fontScale
    fontScale = 5
    # Blue fontColor in BGR
    fontColor = (255, 0, 0)
    # Line fontThickness of 2 px
    fontThickness = 5
    # org
    org = (200, 200)
    cv2.putText(img, timestamp, org, font, fontScale, fontColor, fontThickness, cv2.LINE_AA)

    cv2.imwrite(filename, img)



if __name__ == '__main__':
    files = glob.glob('*.HEIC')

    for f in files:
        # f = os.path.abspath(f)
        print(f)


        # 1
        convertHEICToJPG(f)

        # 2
        timestamp = get_timestamp(f)

        print(timestamp)

        # 3
        nf = f.split('.')[0] + ".jpg"
        add_timestamp(nf, timestamp)

        print('\n')


Leave a Reply