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?
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()
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With