使用 PIL 缓冲到图像

Sae*_*aeX 5 python pillow

我从包含图像的某处接收缓冲区(image_data如下),我想从该缓冲区生成缩略图。

我正在考虑使用 PIL(好吧,枕头),但没有成功。这是我尝试过的:

>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)

我确信有一种简单的方法可以解决这个问题,但我不确定如何解决。

seb*_*sol 8

将您的缓冲区转换为 StringIO,它具有 Image.open() 所需的所有文件对象方法。你甚至可以使用更快的 cStringIO:

from PIL import Image
import cStringIO

def ThumbFromBuffer(buf,size):
    im = Image.open(cStringIO.StringIO(buf))
    im.thumbnail(size, Image.ANTIALIAS)
    return im
Run Code Online (Sandbox Code Playgroud)

  • 对于 python3,StringIO cStringIO 模块已被删除。相反,`from io import StringIO` /sf/ask/834013071/ (3认同)