Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pickleable Image Object

How do I create a pickleable file from a PIL Image object such that you could save those images as a single pickle file then maybe upload to another computer such as a server running PIL and unpickle it there?

like image 426
vijaym123 Avatar asked Apr 12 '12 05:04

vijaym123


2 Answers

You can convert the Image object into data then you can pickle it:

image = {
    'pixels': im.tostring(),
    'size': im.size,
    'mode': im.mode,
}

And back to an Image:

im = Image.fromstring(image['mode'], image['size'], image['pixels'])

NOTE: As astex mentioned, if you're using Pillow (which is recommended instead of PIL), the tostring() method is deprecated for tobytes(). Likewise with fromstring() for frombytes().

like image 152
gak Avatar answered Oct 21 '22 21:10

gak


Slight variation of Gerald's answer using keyword args

create pickleable object

image = {'data': im.tostring(), 'size':im.size, 'mode':im.mode}

or

image = dict(data=im.tostring(), size=im.size, mode=im.mode)

unpickle back to image

im = Image.fromstring(**image)
like image 44
John La Rooy Avatar answered Oct 21 '22 20:10

John La Rooy