Skip to content

Instantly share code, notes, and snippets.

@mozarik
Created March 1, 2021 14:54
Show Gist options
  • Save mozarik/da78a4e3f4f3a6d6152e272cbb84d18b to your computer and use it in GitHub Desktop.
Save mozarik/da78a4e3f4f3a6d6152e272cbb84d18b to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import os
from PIL import Image
OUTPUT_FILE_PATH = "./opt/icons/"
ORIGINAL_FILE_PATH = "./images/"
FILL_COLOR = (120, 8, 220)
def process_image(Image_obj):
""" Take an Image.open() and return Image.open()
object with 90° clockwise and size image to 128 x128 """
Image_obj = Image_obj.resize((128, 128))
Image_obj = Image_obj.rotate(90)
return Image_obj
def saveImgToJPEG(Image_obj, file_path):
""" Take an Image.open() obj and save it to file_path and return success if a file success
to save as JPEG (.jpeg) format
"""
if os.path.exists(OUTPUT_FILE_PATH) == False:
os.makedirs(OUTPUT_FILE_PATH)
# Set Background Color to make the image doesnt go Black after converting
# Background color is set to FILL_COLOR variable
Image_obj = Image_obj.convert('RGBA')
background = Image.new(
Image_obj.mode[:-1], Image_obj.size, FILL_COLOR)
background.paste(Image_obj, Image_obj.split()[-1]) # omit transparency
Image_obj = background
# I dont know why but we have to convert it to RGB and save it
Image_obj.convert("RGB").save(file_path, "JPEG")
print("An image successfully save to {}".format(file_path))
image_file_list = os.listdir(ORIGINAL_FILE_PATH)[1:]
# Setup
for file in image_file_list:
if file == ".DS_Store":
continue
image_path = "{}{}".format(ORIGINAL_FILE_PATH, file)
save_file_path = "{}{}".format(OUTPUT_FILE_PATH, file)
im = Image.open(image_path)
im = process_image(im)
print(im.size)
saveImgToJPEG(im, save_file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment