Sign In

Automate Metadata Preservation After Image Editing with Python

4
Automate Metadata Preservation After Image Editing with Python

Retain Your Creative DNA: Automate Metadata Preservation After Image Editing with Python

In the expansive universe of digital art and photography, metadata not only embeds essential information like copyright, creator details, and editing parameters but also serves as a stepping stone for further creativity. For artists and creators using platforms like Civitai, preserving this data through post-processing phases is crucial for learning and innovation. Today, I’ll guide you through a Python script I developed that automates the preservation of metadata even after the images have been enhanced in Photoshop.

Understanding the Challenge

When images are processed, whether for aesthetic enhancement or format conversion, vital metadata is often stripped away. This loss can be a significant hurdle in platforms where users rely on generation parameters embedded within this metadata to inspire and inform their own creative processes.

The Python Solution

To tackle this, I’ve crafted a Python script that mirrors metadata from a designated "orig" folder to any processed images in the "edit" folder. This method ensures that as long as the original filename string is preserved in the modified file, the metadata remains intact—allowing full transparency and traceability of image parameters.

Running the Script

To ensure the script functions correctly, follow these steps meticulously:

Install Python and Pillow:

  • Download and install Python from Python.org.

  • Open a command line interface and install the Pillow library by running: pip install Pillow.

Setup Your Files:

  • Place the script in the same directory as the "edit" folder, which contains edited images.

  • Ensure all original images you wish to preserve metadata for are stored in a subfolder named "orig".

Execute the Script:

  • Run the script from the directory that contains the "edit" and "orig" folder. The script will automatically search for images in the "orig" folder and mirror their metadata to the processed images in the "edit" folder.

  • The filenames of the edited images in the "edit" folder should include the original filename but can be modified slightly to reflect edits. For example, an original file named 00364-2705041983.png can be saved as 00364-2705041983e.png after edits.

  • The resulting images with mirrored metadata will be saved in the same directory as the script. This method prevents any risk of corrupting the original files in the "orig" and "edit" folders.

Optional:

  • Use the tool TweakPNG to check whether metadata has been correctly applied.

Personal Notes:

  • Ensure the script completes its run to prevent metadata corruption in the target files. If interrupted, simply restart the script to resolve any issues.

  • I want to modify the script in the future so already processed images do get skipped and not overwritten each time the script runs.

  • Once the script has mirrored all the metadata, you can delete the edit folder if you don't plan to use it any further. Image files can become corrupted when their metadata is changed; this is why the original files are left untouched.

Conclusion

With this Python script, you can effortlessly ensure that your creative outputs carry their full generation parameters, no matter how much they are altered or enhanced. This not only aids in organization but also fosters a culture of sharing and learning within the creative community.

The Script

# Script to mirror metadata of png image files
import os
from PIL import Image, PngImagePlugin

def copy_png_metadata(source_path, target_path, output_path):
    # Open the source and target images
    source_image = Image.open(source_path)
    target_image = Image.open(target_path)
    
    # Extract metadata from the source image
    source_info = source_image.info
    
    # Prepare to save metadata to the new file
    pnginfo = PngImagePlugin.PngInfo()
    for key, value in source_info.items():
        pnginfo.add_text(key, str(value))
    
    # Save the target image with metadata to a new file
    target_image.save(output_path, pnginfo=pnginfo)
    print(f"Metadata copied from {source_path} to {output_path}")

def copy_metadata_from_folder(script_dir):
    source_folder = os.path.join(script_dir, "orig")
    target_folder = os.path.join(script_dir, "edit")
    
    # List files in source and target directories
    source_files = {f for f in os.listdir(source_folder) if f.lower().endswith('.png')}
    target_files = {f for f in os.listdir(target_folder) if f.lower().endswith('.png')}
    
    # Copy metadata to new files in the script's directory, appending "_meta" to the filename
    for source_file in source_files:
        source_base = os.path.splitext(source_file)[0]
        for target_file in target_files:
            if source_base in target_file:
                source_path = os.path.join(source_folder, source_file)
                target_path = os.path.join(target_folder, target_file)
                filename, ext = os.path.splitext(target_file)
                output_path = os.path.join(script_dir, filename + "_meta" + ext)
                copy_png_metadata(source_path, target_path, output_path)
                break  # Stop after finding the first match to avoid multiple copies

script_dir = os.path.dirname(os.path.abspath(__file__))
copy_metadata_from_folder(script_dir)
4

Comments