Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffer to Image with PIL

Tags:

python

pillow

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.

like image 840
SaeX Avatar asked Apr 05 '14 11:04

SaeX


People also ask

What is the use of PiL from buffer?

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)

What is the use of image in PIL?

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.

How can I open an image file from a 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).

How do you write a PIL image decoder?

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.


1 Answers

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
like image 158
sebdelsol Avatar answered Sep 20 '22 19:09

sebdelsol