Created
May 22, 2017 21:14
-
-
Save pnettto/5c9fbd331661e6f1b215d7c92334f776 to your computer and use it in GitHub Desktop.
Transform all png images in a directory to jpg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Transform png image to jpg | |
imgs = [] | |
path = "/path/containing/png/files" | |
valid_images = [".png"] | |
for f in os.listdir(path): | |
ext = os.path.splitext(f)[1] | |
if ext.lower() not in valid_images: | |
continue | |
imgs.append({ | |
'name': f, | |
'file': Image.open(os.path.join(path,f)) | |
}) | |
for i in imgs: | |
file = i['file'] | |
name = i['name'] | |
# Has alpha channel | |
if file.mode == 'RGBA': | |
bg = Image.new('RGB', file.size, (255, 255, 255)) | |
bg.paste(file, mask=file.split()[3]) | |
bg.save( os.path.splitext(name)[0] + '.jpg', 'JPEG', quality=95) | |
# Doesn't have alpha channel | |
else: | |
bg.save( os.path.splitext(name)[0] + '.jpg', 'JPEG', quality=95) | |
# Remove PNG file | |
os.remove(os.path.join(path, name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment