Skip to main content
 首页 » 编程设计

python之使用 PIL 缓冲到图像

2025年05月04日18webabcd

我从某处接收到一个包含图像(下面的 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' 
>>> 

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

请您参考如下方法:

将您的缓冲区转换为 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