Skip to content

Instantly share code, notes, and snippets.

@LeFanch
Last active October 23, 2023 09:47
Show Gist options
  • Save LeFanch/3a4de05f59412ff1f2384bea04687e69 to your computer and use it in GitHub Desktop.
Save LeFanch/3a4de05f59412ff1f2384bea04687e69 to your computer and use it in GitHub Desktop.
Keep metadata of image optimized by mozjpeg_lossless_optimization, with piexif
import mozjpeg_lossless_optimization
import piexif
src_file = "source_image.jpg"
out_file = "optimized.jpg"
# Open image
with open(src_file, "rb") as input_jpeg_file:
input_jpeg_bytes = input_jpeg_file.read()
# Get exif data (to dict)
exif_dict = piexif.load(input_jpeg_bytes)
# Optional : this removes the thumbnail from EXIF data
th = exif_dict.pop("thumbnail")
# Image optimization
output_jpeg_bytes = mozjpeg_lossless_optimization.optimize(input_jpeg_bytes)
# Converts the exif dict to bytes
exif_bytes = piexif.dump(exif_dict)
# Optimized image is saved with "old" exif data, by piexif.
piexif.insert(exif_bytes, output_jpeg_bytes, out_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment