Search code examples
pythonpython-imaging-librarypickle

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?


Solution

  • 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().