Skip to content

Instantly share code, notes, and snippets.

@CodeZombie
Created March 20, 2023 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodeZombie/ad498318c30bdf65c04fa81b8400716f to your computer and use it in GitHub Desktop.
Save CodeZombie/ad498318c30bdf65c04fa81b8400716f to your computer and use it in GitHub Desktop.
convert stable diffusion .png images to .jpeg while retaining metadata
from PIL import Image
from PIL.ExifTags import TAGS
import os
SOURCE_DIR = r'C:\Users\jerem\ai\stable-diffusion-webui_working\outputs'
DESTINATION_DIR = r'C:\Users\jerem\ai\converted2'
def find_png_files(directory):
"""Returns a list of full filenames for all .png files in a directory, including subdirectories."""
png_files = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.png'):
png_files.append(os.path.join(root, file))
return png_files
images_completed = 0
all_images = find_png_files(SOURCE_DIR)
print("{} images found".format(len(all_images)))
for filename in all_images:
print("{}%".format(images_completed / len(all_images) * 100))
png_image = Image.open(filename)
png_metadata = png_image.info
jpeg_image = Image.new('RGB', png_image.size)
jpeg_image.putdata(list(png_image.getdata()))
exif = jpeg_image.getexif()
exif[0x9286] = str(png_metadata)
output_filepath = os.path.join(DESTINATION_DIR, os.path.basename(filename)[:-4])
if os.path.exists(output_filepath):
#append the current unix timestamp to the filename
output_filepath += '_' + str(os.path.getmtime(filename))
jpeg_image.save(output_filepath + '.jpeg', exif=exif)
images_completed += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment