Skip to main content
 首页 » 编程设计

Python之枕头缩略图创建错误

2025年02月15日7langtianya

当我尝试从任何图像创建缩略图时,出现此错误:

TypeError: 'int' object has no attribute '__getitem__' 

命令:

./manage.py shell 
from PIL import Image 
i = Image.open('1.jpg') 
i.thumbnail(200) 

错误信息:

--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-6-3e0cd0330e45> in <module>() 
----> 1 i.thumbnail(200) 
 
/home/user/.virtualenvs/project/lib/python2.7/site-packages/PIL/Image.pyc 
in thumbnail(self, size, resample) 
   1828         # preserve aspect ratio 
   1829         x, y = self.size 
-> 1830         if x > size[0]: 
   1831             y = int(max(y * size[0] / x, 1)) 
   1832             x = int(size[0]) 
 
TypeError: 'int' object has no attribute '__getitem__' 

我在某处阅读了一些关于 libjpeg 包的内容,但我对所有类型的文件(gif,png,...) 都遇到了这个错误。

我使用 archlinux:

$ uname -a 
Linux chalist 4.9.11-1-ARCH # 1 SMP PREEMPT  
Sun Feb 19 13:45:52 UTC 2017 x86_64 GNU/Linux 

请您参考如下方法:

大小需要是元组的形式,比如(200, 200)。所以你的新代码将是:

from PIL import Image 
i = Image.open('1.jpg') 
i.thumbnail((200, 200)) 

这是引用网页的链接:http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#create-thumbnails