58 lines
1.1 KiB
Python
58 lines
1.1 KiB
Python
# Convert png image to 256 palette image for Pokitto.
|
|
#
|
|
# author: Miloslav Ciz
|
|
# license: CC0
|
|
|
|
import sys
|
|
from PIL import Image
|
|
|
|
def findClosest(pixel, palettePixels):
|
|
result = 0
|
|
closestDist = 255 * 255 * 255
|
|
|
|
for i in range(256):
|
|
p = palettePixels[i % 16,i / 16]
|
|
d = abs(p[0] - pixel[0]) + abs(p[1] - pixel[1]) + abs(p[2] - pixel[2])
|
|
|
|
if d < closestDist:
|
|
result = i
|
|
closestDist = d
|
|
|
|
if d == 0:
|
|
break
|
|
|
|
return result
|
|
|
|
image = Image.open(sys.argv[1])
|
|
pixels = image.load()
|
|
|
|
pal = Image.open(sys.argv[2])
|
|
palPixels = pal.load()
|
|
|
|
outImage = Image.new("RGB",(image.size[0],image.size[1]),"white")
|
|
outPixels = outImage.load()
|
|
|
|
sys.stdout.write("const unsigned char image[] =\n{ ")
|
|
sys.stdout.write(str(image.size[0]) + ", " + str(image.size[1]) + " // width, height")
|
|
|
|
count = 0
|
|
|
|
for x in range(image.size[0]):
|
|
for y in range(image.size[1]):
|
|
if count % 14 == 0:
|
|
sys.stdout.write("\n ");
|
|
|
|
p = pixels[x,y]
|
|
|
|
closest = findClosest(p,palPixels)
|
|
|
|
sys.stdout.write(",0x{:02x}".format(closest))
|
|
|
|
outPixels[x,y] = palPixels[closest % 16,closest / 16]
|
|
|
|
count += 1
|
|
|
|
print("\n};")
|
|
|
|
outImage.save("out.png")
|
|
|