Python PIL NameError 全局名称 未定义图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20443846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:27:02  来源:igfitidea点击:

Python PIL NameError global name Image is not defined

pythonpython-imaging-librarypython-requests

提问by Mayank Kumar

I installed PIL 1.1.7 using the executable for Python 2.7. But when I run this code :

我使用 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()

It gives the error :

它给出了错误:

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

I installed PIL in Lib\site-packages.

我在Lib\site-packages.

采纳答案by Peter Gibson

You need to explicitly import the Image module:

您需要显式导入 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'>
>>>

Or just

要不就

>>> import Image

回答by vartec

Use

from PIL import Image

This way it will work, and your code will be forward-compatible with Pillow. On the other hand, import Imagewill notwork with Pillow.

这样它就可以工作,并且您的代码将与Pillow向前兼容。在另一方面,import Image与枕头工作

The development of PIL has been stopped in mid 2011, without any official announcement or explication. Pillow is a fork of original PIL and is actively developed.

PIL的开发于2011年年中停止,没有任何官方公告或说明。Pillow 是原始 PIL 的一个分支,并且正在积极开发中。

回答by Chaitanya

If

如果

import Image

is not working. Try:

不管用。尝试:

from PIL import Image

There is compatibility issue with all the packages in PIL. Try downloading PIL package manually for the latest version. Actually worked with this in Python 3.2 Version, everything is working fine.

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