Skip to content

Instantly share code, notes, and snippets.

@benstigsen
Created October 29, 2019 21:47
Show Gist options
  • Save benstigsen/fe9040d3e150c9ade25e41ed31aba9ee to your computer and use it in GitHub Desktop.
Save benstigsen/fe9040d3e150c9ade25e41ed31aba9ee to your computer and use it in GitHub Desktop.
Convert all PNG images in a folder (including subdirectories), to JPG.
import os
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
def convert(folder_path, delete_old = True):
for root, dirs, files in os.walk(folder_path):
print(root)
for filename in files:
if ".png" in filename:
try:
print(f"Converting {folder_path}/{filename}")
im = Image.open(os.path.join(root, filename))
rgb_im = im.convert('RGB')
rgb_im.save(os.path.join(root, f"{filename[:-4]}.jpg"))
print(f"Converted {folder_path}/{filename}")
except (IOError, MemoryError):
#os.remove(os.path.join(root, filename))
pass
# Remove original image if already converted
if delete_old and f"{filename[:-4]}.jpg" and f"{filename[:-4]}.png" in files:
print(f"Deleting image: {filename[:-4]}.png")
os.remove(os.path.join(root, f"{filename[:-4]}.png"))
print()
convert(input("Path to folder: "))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment