[Image-SIG] fromstring() question...

Fredrik Lundh fredrik@pythonware.com
Tue, 23 Mar 1999 09:13:45 +0100

David Jeske <jeske@egroups.net> wrote:
> I'm having trouble figuring out what I'm supposed to do to get
> fromstring() to work.

Ignore it ;-)

> What I _want_ to do is: hand fromstring() a string which _is_ the
> contents of an image file, plus the encoder type (derived from the
> mime type), and have it pass back the PIL Image it retrieved as a
> result of decoding that string.

PIL autodetects all major formats, so you can simply ignore
the mime type, and stuff your data into a StringIO object:

im = Image.open(StringIO.StringIO(data))

(fromstring is designed to unpack pixel data chunks from a
file into an image memory; it doesn't parse file headers).

but if you insist in identifying the files yourself, you could
roll your own image loader.  the following snippet shows
how to use the MIME and OPEN registries to pick the right
image factory from the start.

import Image
import StringIO


MAP = {}

# preload handlers
for tag in ("GIF", "JPEG"):
    MAP[Image.MIME[tag]] = Image.OPEN[tag]

def image_from_data(data, mime):
    # disclaimer: this works with PIL 1.0 and earlier. it
    # may not work with future releases.
    factory, accept = MAP[mime]
    if not accept or accept(data):
        fp = StringIO.StringIO(data)
        return factory(fp, "")
    raise IOError, "invalid image file"

data = open("/images/sample.jpg", "rb").read()
im = image_from_data(data, "image/jpeg")

Cheers /F