[Image-SIG] PIL and converting an image to and from a string value
chris.barker at noaa.gov
Fri Apr 27 17:50:47 CEST 2012
On Fri, Apr 27, 2012 at 6:21 AM, Charles Cazabon
<charlesc-pyimagesig at pyropus.ca> wrote:
>> I am stuck however, in figuring out how to take the string data and
>> converting it back to an image that I can put into the canvas widget.
> See the PIL handbook, where it says "If you have an entire image file in a
> string, wrap it in a StringIO object, and use open to load it."
Actually, I don't think that's what the OP wants. A couple notes:
1) "string" is a confusing term -- generally it means text, but in
python (2.*) it means "an arrbitrary sequence of bytes, that can be
interpreteed as text depending on context" -- that is why there is now
a "string" object and a "bytes" object. IN py2, bytes and string are
the same, but it's handy to use bytes for future compatibility with
py3, and for clarity in your code.
So in this case, we are talking about bytes objects.
(side note: make sure you are storing bytes objects in your DB
properly -- as a binary blob, so that it doens't mess with the data)
Now the real point: you can store an image in two ways (at least) in a
1) essentially a binary dump of what would be in an encoced file (PNG,
whatever). This is would you
d get if you did:
the_image_bytes = file("an_image.png", 'rb').read()
2) a binary dump of the bytes in memeory of the image object, without
encoding or compression -- this is waht you get whn you do:
the_image_bytes = a_pil_image.tostring()
The STringIO suggestion refers to the former, but I thikn the OP was
dealing with the later.
In the later case, you can re-construct teh image object with:
Image.fromstring(mode, size, data) => image
a_pil_image = Image.fromstring('RGB', (300, 500), the_image_bytes)
note that you'll need to keep track of what the made and size of the
image are -- PIL can't figure that out just from the data.
Depending on your needs, you may in fact want to store the PNG-encoded
bytes in the DB, and decode them when you pull them out, using the
Christopher Barker, Ph.D.
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the Image-SIG