#!/usr/bin/python
"""image2cisco v0.1
Copyright 2008 Michael Farrell <http://micolous.id.au/>

Converts a PIL supported image to a CIP (Cisco IP Phone Image) file.  Assumes 2-bit-per-pixel (4 colour) output.

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""
from PIL import Image
from sys import argv, exit


if len(argv) != 3:
	print "image2cisco v0.1 by Michael Farrell"
	print "Usage: %s <input image> <output cip>" % argv[0]
	exit(1)
	
im = Image.open(argv[1])
fh = open(argv[2], "w")

print "Converting", argv[1], "to cisco image", argv[2], "..."
print "Image size is", im.size

for y in range(im.size[1]):
	for x in range(0,im.size[0],4):
		pix1 = im.getpixel((x,y))
		pix2 = 0
		pix3 = 0
		pix4 = 0
		if x+1<im.size[0]:
			pix2 = im.getpixel((x+1,y))
		if x+2<im.size[0]:
			pix3 = im.getpixel((x+2,y))
		if x+3<im.size[0]:
			pix4 = im.getpixel((x+3,y))
		
		#print "read %s,%s,%s,%s" % (pix1, pix2, pix3, pix4)
		# we have pixels, lets shrink and invert
		pix1 = (255-pix1) / 64
		pix2 = (255-pix2) / 64
		pix3 = (255-pix3) / 64
		pix4 = (255-pix4) / 64
		
		# now pack it into one int!
		out = (pix4 << 6) + (pix3 << 4) + (pix2 << 2) + pix1
		
		# and write to file.
		#print "%02X/%s pixels %s,%s,%s,%s" % (out, out, pix1, pix2, pix3, pix4)
		fh.write("%02X" % out)
	fh.write(":")

fh.flush()
fh.close()

print "Done."
		
		
		
			
		

