Skip to content

Instantly share code, notes, and snippets.

@saltyfireball
Last active August 10, 2018 15:40
Show Gist options
  • Select an option

  • Save saltyfireball/9b27343c8153f94a4ae32d8b090056c8 to your computer and use it in GitHub Desktop.

Select an option

Save saltyfireball/9b27343c8153f94a4ae32d8b090056c8 to your computer and use it in GitHub Desktop.
Using Pillow to Convert jpg to png

Using Pillow to Convert jpg to png

Simple script to list all files in a files in a directory

*This assumes all files in folder are png images.

import os
from PIL import Image

image_path = '../tmp/'
image_path_jpg = image_path + 'jpg/'

images = [f for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f))]

for file in images:
    im = Image.open(image_path + file)
    if im.mode == 'RGBA':
        background = Image.new(im.mode[:-1], im.size, '#ffffff')
        background.paste(im, im.split()[-1])
        background.save(image_path_jpg + os.path.splitext(os.path.basename(file))[0] + '.jpg')
    else:
        im = im.convert('RGB')
        im.save(image_path_jpg + os.path.splitext(os.path.basename(file))[0] + '.jpg')
import os
from PIL import Image
image_path = '../tmp/'
image_path_jpg = image_path + 'jpg/'
images = [f for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f))]
for file in images:
im = Image.open(image_path + file)
if im.mode == 'RGBA':
background = Image.new(im.mode[:-1], im.size, '#ffffff')
background.paste(im, im.split()[-1])
background.save(image_path_jpg + os.path.splitext(os.path.basename(file))[0] + '.jpg')
else:
im = im.convert('RGB')
im.save(image_path_jpg + os.path.splitext(os.path.basename(file))[0] + '.jpg')
@saltyfireball
Copy link
Author

saltyfireball commented Aug 10, 2018

can change to this if you want to be more specific with the file listing.

import os
from PIL import Image

image_path = '../tmp/'
image_path_jpg = image_path + 'jpg/'

# images = [f for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f))]
files = []
for file in os.listdir(image_path):
    if file.endswith(".png"):
        files.append(file)

for file in files:
    im = Image.open(image_path + file)
    print(os.path.splitext(os.path.basename(file))[0], file)
    print(im.mode)
    if im.mode == 'RGBA':
        background = Image.new(im.mode[:-1], im.size, '#ffffff')
        background.paste(im, im.split()[-1])
        background.save(image_path_jpg + os.path.splitext(os.path.basename(file))[0] + '.jpg')
    else:
        im = im.convert('RGB')
        im.save(image_path_jpg + os.path.splitext(os.path.basename(file))[0] + '.jpg')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment