Reputation: 18781
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.
Upvotes: 5
Views: 21695
Reputation: 1085
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
Upvotes: 9
Reputation: 18781
For the sake of completeness, here's what my code ended up to be (with the appreciated help).
def picture_small(request, pk):
try:
image_data = Person.objects.get(pk=pk).picture
im = Image.open(cStringIO.StringIO(image_data))
im.thumbnail((50, 70), Image.ANTIALIAS)
image_buffer = cStringIO.StringIO()
im.save(image_buffer, "JPEG")
response = HttpResponse(image_buffer.getvalue(), content_type="image/jpeg")
return response
except Exception, e:
raise Http404
Using Django 1.6.
Upvotes: 2