Pillow: Image.tobytes Call Format for Non-raw Encoders

Created on 3 Nov 2014  路  2Comments  路  Source: python-pillow/Pillow

Hi all,

Having a bit of a problem with Image.tobytes with non-"raw" encoders:

img.tobytes()

and the explicit:

img.tobytes('raw')

Both work fine, but something like:

img.tobytes('gif')

gives me the following error:

File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 650, in tobytes
    e = _getencoder(self.mode, encoder_name, args)
File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 430, in _getencoder
    return encoder(mode, *args + extra)
TypeError: function takes at least 2 arguments (1 given)

Any guidance here? Honestly can't work out if I'm being the world's biggest noob or if something's amiss here!

Most helpful comment

That's unlikely to work.

If you want to get the image encoded as a gif, what you should do is something like this:

import io
from PIL import Image
im = Image.open('some image path')
[do stuff here]
b = io.BytesIO()
im.save(b, 'GIF')
image_bytes = b.getvalue()

The arguments to tobytes are somewhat obscure and as far as I know, only used for a couple very close to raw formats. Anything that does much extra processing, like GIF, is going to fail unless you essentially duplicate all the work that the GifImagePlugin does to setup the encoder.

This should probably be noted in the docs.

All 2 comments

That's unlikely to work.

If you want to get the image encoded as a gif, what you should do is something like this:

import io
from PIL import Image
im = Image.open('some image path')
[do stuff here]
b = io.BytesIO()
im.save(b, 'GIF')
image_bytes = b.getvalue()

The arguments to tobytes are somewhat obscure and as far as I know, only used for a couple very close to raw formats. Anything that does much extra processing, like GIF, is going to fail unless you essentially duplicate all the work that the GifImagePlugin does to setup the encoder.

This should probably be noted in the docs.

Aah, OK :) I agree, it's somewhat mysterious. If you dig into what your "raw" eventually gets translated to, it's raw_encoding (from memory) in core - which happens to be right next to gif_encoding, jpeg_encoding etc! Gave me the impression those ones could be used to.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nomarek picture nomarek  路  3Comments

hxzhao527 picture hxzhao527  路  4Comments

vytisb picture vytisb  路  4Comments

Larivact picture Larivact  路  4Comments

edowson picture edowson  路  3Comments