用PIL将缓冲区转换为图像

5 投票
2 回答
20094 浏览
提问于 2025-04-18 01:28

我从某个地方收到了一个包含图片的缓冲区(下面的image_data),我想从这个缓冲区生成一个缩略图。

我想用PIL(其实是Pillow)来处理,但没有成功。以下是我尝试过的:

>>> 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'
>>>

我相信有简单的方法可以解决这个问题,但我不知道该怎么做。

2 个回答

2

为了完整起见,这里是我最终的代码(感谢大家的帮助)。

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

使用的是Django 1.6版本。

9

把你的缓冲区转换成一个StringIO对象,这个对象有打开图片所需的所有文件方法。你甚至可以使用cStringIO,它的速度更快:

from PIL import Image
import cStringIO

def ThumbFromBuffer(buf,size):
    im = Image.open(cStringIO.StringIO(buf))
    im.thumbnail(size, Image.ANTIALIAS)
    return im

撰写回答