Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
convert image file to nine-patch and remove duplicate pixels
#!/usr/bin/env python
# encoding: utf-8
# depends on
# pip install pillow numpy
from PIL import Image
import numpy as np
import sys
import os
def isPixelEqual(lhs, rhs):
eq = lhs == rhs
# if eq is ndar
if isinstance(eq, np.ndarray):
return reduce(lambda x, y: x and y, eq, True)
else:
return eq
def isLineEqual(lhs, rhs):
for i in range(0, lhs.shape[0]):
if not isPixelEqual(lhs[i], rhs[i]):
return False
return True
def stripDuplicateColumns(pixels):
i = 1
while i < pixels.shape[1]:
if (isLineEqual(pixels[:, i - 1], pixels[:, i])):
# delte line i
pixels = np.delete(pixels, (i), axis=1)
else:
i += 1
return pixels
def stripDuplicateRows(pixels):
i = 1
while i < pixels.shape[0]:
if (isLineEqual(pixels[i - 1], pixels[i])):
# delete line i
pixels = np.delete(pixels, (i), axis=0)
else:
i += 1
return pixels
def stripDuplicatePixels(pixels):
pixels = stripDuplicateRows(pixels)
pixels = stripDuplicateColumns(pixels)
return pixels
def strideForMode():
# RGBA
return (np.array([0, 0, 0, 255]), np.array([255, 255, 255, 0]))
def addNinePatchStride(pixels):
black, white = strideForMode()
shape = pixels.shape
nw = shape[0] + 2
nh = shape[1] + 2
if (len(shape) == 3):
nine = np.ndarray((shape[0] + 2, shape[1] + 2, shape[2]), np.uint8)
else:
nine = np.ndarray((shape[0] + 2, shape[1] + 2), np.uint8)
# copy pixels
for row in range(0, nw):
for col in range(0, nh):
if row == 0:
# scale
nine[row, col] = black if col == (nw / 2) else white
elif row == nw - 1:
# padding
nine[row, col] = white if col == 0 or col == nw - 1 else black
elif col == 0:
# scale
nine[row, col] = black if row == (nh / 2) else white
elif col == nh - 1:
# padding
nine[row, col] = white if row == 0 or row == nh - 1 else black
else:
nine[row, col] = pixels[row - 1, col - 1]
return nine
def createNinePatch(file):
pixels = Image.open(file).convert("RGBA")
array = np.array(pixels)
output = stripDuplicatePixels(array)
ninePatch = addNinePatchStride(output)
outputImg = Image.fromarray(ninePatch, mode="RGBA")
return outputImg
def createNinePatchFile(file):
path = os.path.realpath(file)
dir = os.path.dirname(path)
name = os.path.basename(path)
index = name.rfind(".")
if index != -1:
ninePatchName = name[0:index] + ".9" + name[index:]
else:
ninePatchName = name + ".9"
ninePatchFile = os.path.join(dir, ninePatchName)
outputImg = createNinePatch(path)
outputImg.save(ninePatchFile, "png")
return ninePatchFile
if __name__ == '__main__':
if len(sys.argv) < 2:
print sys.argv[0] + " [-r] <image file>"
print " -r delete original file"
else:
replace = '-r' in sys.argv
file = createNinePatchFile(sys.argv[1] if not replace else sys.argv[2])
if replace:
os.remove(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment