I'm receiving a buffer from somewhere that contains an image (image_data
below), and I'd like to generate a thumbnail from that buffer.
I was thinking to use PIL (well, Pillow), but no success. Here's what I've tried:
>>> image_data
<read-only buffer for 0x03771070, size 3849, offset 0 at 0x0376A900>
>>> im = Image.open(image_data)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<path>\PIL\Image.py", line 2097, in open
prefix = fp.read(16)
AttributeError: 'buffer' object has no attribute 'read'
>>> image_data.thumbnail(50, 50)
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'buffer' object has no attribute 'thumbnail'
>>>
I'm sure there is an easy way to fix this, but I'm not sure how.
PIL.Image.frombuffer () Creates an image memory referencing pixel data in a byte buffer. Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a BytesIO object, and use open () to load it. Syntax: PIL.Image.frombuffer (mode, size, data, decoder_name=’raw’, *args)
The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. PIL.Image.frombuffer () Creates an image memory referencing pixel data in a byte buffer.
Convert your buffer to a StringIO, which has all the file object's methods needed for Image.open (). You may even use cStringIO which is faster: Show activity on this post. For the sake of completeness, here's what my code ended up to be (with the appreciated help).
Syntax: PIL.Image.frombuffer (mode, size, data, decoder_name=’raw’, *args) mode – The image mode. See: Modes size – The image size. data – A byte buffer containing raw data for the given mode. decoder_name – What decoder to use. args – Additional parameters for the given decoder.
Convert your buffer to a StringIO, which has all the file object's methods needed for Image.open(). You may even use cStringIO which is faster:
from PIL import Image
import cStringIO
def ThumbFromBuffer(buf,size):
im = Image.open(cStringIO.StringIO(buf))
im.thumbnail(size, Image.ANTIALIAS)
return im
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