Last active
July 14, 2016 01:55
-
-
Save rutcreate/aa26b31d735d8dfe6db6640b10ef66e2 to your computer and use it in GitHub Desktop.
Expand image's canvas to Power of 2.
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
#!/usr/bin/env python | |
from PIL import Image | |
import math | |
import os | |
from glob import glob | |
allowed_sizes = [2, 4, 8, 16, 64, 128, 256, 512, 1024, 2048] | |
def resize(): | |
cwd = os.getcwd() | |
result = [y for x in os.walk(cwd) for y in glob(os.path.join(x[0], '*.png'))] | |
for filepath in result: | |
im = Image.open(filepath) | |
image_width, image_height = im.size; | |
if not is_pot(image_width, image_height): | |
generate_pot_image(filepath) | |
result = [y for x in os.walk(cwd) for y in glob(os.path.join(x[0], '*.jpg'))] | |
for filepath in result: | |
im = Image.open(filepath) | |
image_width, image_height = im.size; | |
if not is_pot(image_width, image_height): | |
generate_pot_image(filepath) | |
def generate_pot_image(filepath): | |
im = Image.open(filepath) | |
image_width, image_height = im.size; | |
if image_width > image_height: | |
image_size = image_width | |
else: | |
image_size = image_height | |
# Find POT size which fit for image. | |
canvas_size = 0 | |
for size in allowed_sizes: | |
if size > image_size: | |
canvas_size = size | |
break | |
if canvas_size > 0: | |
destination_filepath = os.path.splitext(filepath)[0] + '.png'; | |
# Center the image | |
x = int(math.floor((canvas_size - image_width) / 2)) | |
y = int(math.floor((canvas_size - image_height) / 2)) | |
# Create POT canvas. | |
newImage = Image.new('RGBA', (canvas_size, canvas_size), 255) | |
newImage.paste(im, (x, y, x + image_width, y + image_height)) | |
newImage.save(destination_filepath) | |
print destination_filepath | |
if os.path.splitext(filepath)[-1] == '.jpg': | |
# Delete original JPG file. | |
os.remove(filepath) | |
# Remove meta file to keep reference. | |
jpg_meta_filepath = filepath + '.meta' | |
png_meta_filepath = os.path.splitext(filepath)[0] + '.png.meta' | |
if os.path.isfile(jpg_meta_filepath): | |
os.rename(jpg_meta_filepath, png_meta_filepath) | |
def is_pot(width, height): | |
if (width != height): return False | |
return width > 0 and ((width & (width - 1)) == 0) | |
resize() | |
# How to use | |
# python pot_images.py /path/to/images/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment