[Image-SIG] Creating an image from <canvas>'s getImageData() data
Fredrik Lundh
fredrik at pythonware.com
Tue Dec 9 19:00:10 CET 2008
On Tue, Dec 9, 2008 at 5:35 PM, Fredrik Lundh <fredrik at pythonware.com> wrote:
> The "raw" data decoder expects raw binary bytes; in this case, it
> expects four bytes per pixel (<red> <green> <blue> <alpha>), repeated
> 80x80 times to fill the entire image. What does the data you get back
> from getImageData() look like if you print (a portion of) it? e.g.
> say
>
> print repr(data[:40])
>
> (That "replace" you're using makes me think that you have data in text
> form, not binary form...)
And for the record, here's a fairly efficient way to convert
comma-separated pixel values into a PIL Image object:
>>> data = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16"
>>> import Image
>>> import array
>>> a = array.array("b", map(int, data.split(",")))
>>> a
array('b', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
# turn it into a grayscale image (one byte per pixel)
>>> i = Image.frombuffer("L", (4, 4), a, "raw", "L", 0, 1)
>>> i.mode
'L'
>>> list(i.getdata())
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
# turn it into an RGBA image (four bytes per pixel)
>>> i = Image.frombuffer("RGBA", (1, 4), a, "raw", "RGBA", 0, 1)
>>> i.mode
'RGBA'
>>> list(i.getdata())
[(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)]
</F>
More information about the Image-SIG
mailing list