[Image-SIG] Converting to zebra (ZPL) format
Fredrik Lundh
fredrik at pythonware.com
Fri Jun 17 09:40:43 CEST 2005
Peter Dempsey wrote:
> Hi folks, I'm a newbie to python so please be gentle.
>
> I want to convert an image to a format suitable for use in a Zebra label
> printer. The data sent to the printer consists of a string of hex characters.
> Each byte converts to a binary set of dots on the label.
>
> FF becomes 11111111
> A5 becomes 10100101
>
> So a string like this becomes a right-angle triangle...
>
> 18,3^m
> F00000FF0000FFF000FFFF00FFFFF0FFFFFF
>
> The 18 says how many bytes in the image, 3 says how many bytes wide the image
> is. So the string above becomes...
>
> F00000 -> 111100000000000000000000
> FF0000 -> 111111110000000000000000
> FFF000 -> 111111111111000000000000
> FFFF00 -> 111111111111111100000000
> FFFFF0 -> 111111111111111111110000
> FFFFFF -> 111111111111111111111111
>
> I'm sure it's a simple task, I mean, the image is converted to a hex
> representation of the raw image.
>
> I've had some success doing it the hard way with python, importing a pcx image
> and going through it byte by byte but I'm sure there's an easier way.
>
> Any suggestions would be super.
how about:
import Image
#
# step 1) convert example to pil image
data = (
"111100000000000000000000",
"111111110000000000000000",
"111111111111000000000000",
"111111111111111100000000",
"111111111111111111110000",
"111111111111111111111111",
)
height = len(data)
width = len(data[0])
im = Image.new("1", (width, height), 0)
# convert data to list of values
pixels = []
for row in data:
pixels.extend([1-int(ch) for ch in row])
im.putdata(pixels)
#
# step 2) convert it back to a hex string
data = im.tostring("raw", "1;I")
size = len(data)
data = ["%02X" % ord(byte) for byte in data]
print "%d,%d^m" % (size, (im.size[0]+7)/8)
print "".join(data)
# end
things to notice:
- step 1 can of course be replaced with some other way
to create a mode "1" image
- mode "1" images treat "1" as white and "0" as black.
- the tostring arguments are a bit magical. some info can
be found here: http://effbot.org/imagingbook/decoder.htm
- [blah for blah in blah] is a list comprehension. if you're
using Python 2.4, you can omit the brackets (which turns
it into a generator expression, but the result is the same)
- (blah+7)/8 converts the number of pixels to a number of
bytes, rounding up to the nearest byte. to be future safe,
you might wish to use "//" instead of "/".
</F>
More information about the Image-SIG
mailing list