Mosquito-Alert / mosquito_alert

The Django app behind Mosquito Alert platform.
https://webserver.mosquitoalert.com
Other
7 stars 4 forks source link

Remove sensitive EXIF metadata #174

Open epou opened 10 months ago

epou commented 10 months ago

Example

import piexif
from PIL import Image

def remove_sensitive_data(input_image_path, output_image_path):
    # Open the image using Pillow (PIL)
    image = Image.open(input_image_path)

    # Get the Exif data from the image
    exif_dict = piexif.load(image.info["exif"])

    # Remove sensitive fields from the Exif data
    sensitive_tags = [
        piexif.ExifIFD.Artist,  # Artist/Author information
        piexif.ExifIFD.DateTimeOriginal,  # Date and time when the photo was taken
        piexif.GPSIFD.GPSLatitude,  # GPS Latitude
        piexif.GPSIFD.GPSLongitude,  # GPS Longitude
        piexif.ImageIFD.Make,  # Camera make
        piexif.ImageIFD.Model,  # Camera model
    ]

    for ifd in ("0th", "Exif", "GPS", "1st"):
        for tag in sensitive_tags:
            if tag in exif_dict[ifd]:
                exif_dict[ifd].pop(tag)

    # Save the modified Exif data back to the image
    exif_bytes = piexif.dump(exif_dict)
    image.save(output_image_path, exif=exif_bytes)

# Example usage
input_image_path = "input.jpg"
output_image_path = "output.jpg"
remove_sensitive_data(input_image_path, output_image_path)

Also see: https://github.com/Mosquito-Alert/mosquito_alert/issues/52

epou commented 9 months ago

Be aware of the EXIF.Orientation tag.

@nikaxx proposed two possible solutions:

  1. retain the original EXIF orientation metadata.
  2. rotate the image based on the EXIF orientation metadata value, save the already rotated image to the server, and remove the tag completely or reset the EXIF orientation tag to "0".

A value of "0" in EXIF orientation tag signifies that the tag should be ignored according to the documentation.

nikaxx commented 9 months ago

Please also note to transform previous images that are already on the server, after choosing one of the two proposed solutions to keep the consistency.

nikaxx commented 9 months ago

Example of how to find EXIF orientation tag:

from PIL import Image, ExifTags, ImageOps
from PIL.ExifTags import TAGS 

# find exif orientation metadata of an image
def find_image_exif_orientation(original_image_file):
    orientation = None
    with Image.open(original_image_file) as pilImg:
        img_exif = pilImg.getexif()
        if img_exif is not None:
            for key, val in img_exif.items():
                if key in ExifTags.TAGS and key == 274:
                    orientation = val
                #print('{}: {} key number:{}'.format(TAGS[key], val, key))
    return orientation