Python PIL NameError全局名称Image未定义

13

我使用Python 2.7的可执行文件安装了PIL 1.1.7。但是当我运行以下代码时:

import requests
from PIL import *

def main() :
    target = "http://target/image.php" #returns binary data for a PNG.
    cookies = {"mycookie1", "mycookie2"}
    r = requests.get(target, cookies=cookies)
    im = Image.open(r.content) #r.content contains binary data for the PNG.
    print im

if __name__ == "__main__" :
    main()

它报错了:

Traceback (most recent call last):
File "D:\Programming\Python\code\eg_cc1.py", line 17, in <module>
  main()
File "D:\Programming\Python\code\eg_cc1.py", line 13, in main
  im = Image.open(r.content)
NameError: global name 'Image' is not defined

我在Lib\site-packages中安装了PIL。

3个回答

15

您需要显式导入Image模块:

>>> from PIL import *
>>> Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Image' is not defined
>>> import PIL.Image
>>> Image
<module 'Image' from 'c:\Python27\lib\site-packages\PIL\Image.pyc'>
>>>

或者只需要

>>> import Image

13
from PIL import Image

这样做可以起作用,并且您的代码将与Pillow兼容。另一方面,import Image 将无法与Pillow一起使用

PIL的开发在2011年中期停止,没有任何官方公告或解释。Pillow是原始PIL的分支版本,并正在积极开发中。


(在这里留言2017年)谢谢,这是唯一有效的方法。 - maaw
全局名称 'PIL' 未定义。 - Eddie

5
如果
import Image

没有工作。 尝试:

from PIL import Image

所有的 PIL 包都存在兼容性问题。尝试手动下载最新版本的 PIL 包。 在 Python 3.2 版本 中,一切工作正常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接