Pickle an image?

M.E.Farmer mefjr75 at hotmail.com
Tue Apr 26 00:46:54 EDT 2005


GMane Python wrote:
> Hey all.
>   I have a ( list | tuple | dictionary ) with several graphics in it.
> Trying to cPickle it to a file, I get errors.  For instance,
> UnpickleableError: Cannon pickle <type 'ImagingCore'> objects.
>
>   Anyone know of a way to get around this?  I'd like to pickle a list
or
> dictionary of about 5 .JPG images.
>
> Thanks!
> Dave
Open your images in binary mode and read them in as binary strings then
save them in a list/dict/tuple , then pickle it.
>>> import Image, pickle, cStringIO
>>> i = open('c:/1.jpg', 'rb')
>>> i.seek(0)
>>> w = i.read()
>>> i.close()
>>> dic =  {'1':w,'2':w,'3':w,'4':w}
>>> p = pickle.dumps(dic)
# storage would happen at this point

Ok now you take your pickled string and unpickle your object and select
the item you want and put it in a cStringIO or StringIO so we can open
it directly with PIL.
# sometime in the future
>>> o = pickle.loads(p)
>>> one_im = o['1']
>>> c = StringIO.StringIO()
>>> c.write(one_im)
>>> c.seek(0)
>>> im = Image.open(c)
>>> im.show()

Alternatively you can create a StringIO object and pickle that in your
dictionary so you can just load it later with PIL.

Pickling will bloat the size of your file so you might want to use some
compression, although most formats will compress very little the
pickling overhead can __mostly__ be avoided.
There are boundless ways to do this and this just one of them.
hth,
M.E.Farmer




More information about the Python-list mailing list