2005-11-08 10:18:09 +01:00
|
|
|
#!/usr/bin/python
|
|
|
|
from PIL import Image
|
|
|
|
import sys
|
2005-11-09 20:10:38 +01:00
|
|
|
import os
|
2005-11-09 21:29:56 +01:00
|
|
|
import struct
|
2005-11-09 23:56:00 +01:00
|
|
|
from getopt import gnu_getopt
|
2005-11-08 10:18:09 +01:00
|
|
|
|
|
|
|
"""Convert image to raw binary using Python Imaging Library."""
|
|
|
|
|
2005-11-09 21:29:56 +01:00
|
|
|
def split_seq(seq, splitsize):
|
|
|
|
newseq = []
|
|
|
|
while seq:
|
|
|
|
newseq.append(seq[:splitsize])
|
|
|
|
seq = seq[splitsize:]
|
2005-11-10 00:10:57 +01:00
|
|
|
return newseq
|
2005-11-08 10:18:09 +01:00
|
|
|
|
2005-11-10 00:10:57 +01:00
|
|
|
def write_block(f, image, width=8, height=8, offset_x=0, offset_y=0):
|
|
|
|
for y in range(height):
|
|
|
|
for x in range(width):
|
|
|
|
val = image.getpixel((x+offset_x, y+offset_y))
|
|
|
|
f.write(chr(val))
|
|
|
|
|
2005-11-09 21:29:56 +01:00
|
|
|
if __name__=="__main__":
|
2005-11-09 23:56:00 +01:00
|
|
|
|
|
|
|
tiled, args = gnu_getopt(sys.argv[1:], "t")
|
|
|
|
|
|
|
|
if len(args) < 2:
|
|
|
|
print "Usage: %s [-t] <source> <target> [palette]" % os.path.split(sys.argv[0])[1]
|
|
|
|
print " -t - Convert data in 8x8 pixel tiles in 1D layout."
|
2005-11-09 21:29:56 +01:00
|
|
|
sys.exit()
|
2005-11-08 10:18:09 +01:00
|
|
|
|
2005-11-09 23:56:00 +01:00
|
|
|
im = Image.open(args[0])
|
|
|
|
output = open(args[1], "wb")
|
2005-11-09 21:29:56 +01:00
|
|
|
width, height = im.size
|
2005-11-09 21:46:28 +01:00
|
|
|
print "Converting %dx%d image to binary." % (width, height)
|
2005-11-09 23:56:00 +01:00
|
|
|
if not tiled:
|
2005-11-10 00:10:57 +01:00
|
|
|
write_block(output, im, width, height)
|
2005-11-09 23:56:00 +01:00
|
|
|
else:
|
|
|
|
print "Doing 1D tile conversion."
|
|
|
|
if (width % 8) or (height % 8):
|
|
|
|
print "Can't tile image where width or height is not multiple of 8."
|
|
|
|
exit(-1)
|
|
|
|
else:
|
|
|
|
for offset_y in map(lambda n : 8*n, range(height / 8)):
|
|
|
|
for offset_x in map(lambda n : 8*n, range(width / 8)):
|
2005-11-10 00:10:57 +01:00
|
|
|
write_block(output, im, offset_x=offset_x, offset_y=offset_y)
|
2005-11-08 10:18:09 +01:00
|
|
|
|
2005-11-09 23:56:00 +01:00
|
|
|
if len(args) > 2:
|
|
|
|
pal_output = open(args[2], "wb")
|
2005-11-09 21:46:28 +01:00
|
|
|
print "Converting %d color palette." % (len(im.palette.palette) / 3)
|
2005-11-09 21:43:18 +01:00
|
|
|
for color in split_seq(im.palette.palette, 3):
|
2005-11-09 21:29:56 +01:00
|
|
|
r, g, b = map(lambda col : col >> 3, map(ord, color))
|
|
|
|
|
|
|
|
value = (b << 10) + (g << 5) + r
|
|
|
|
pal_output.write(struct.pack("<h", value))
|