Python PIL NameError global name Image is not defined

Question:

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

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:ProgrammingPythoncodeeg_cc1.py", line 17, in <module>
  main()
File "D:ProgrammingPythoncodeeg_cc1.py", line 13, in main
  im = Image.open(r.content)
NameError: global name 'Image' is not defined

I installed PIL in Libsite-packages.

Asked By: Mayank Kumar

||

Answers:

You need to explicitly import the Image module:

>>> 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:Python27libsite-packagesPILImage.pyc'>
>>>

Or just

>>> import Image
Answered By: Peter Gibson

Use

from PIL import Image

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

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.

Answered By: vartec

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.

Answered By: Chaitanya

Reading image from url

import request
image = Image.open ( requests.get(‘https://images.app.goo.gl/7p3bkztHyDAYDS2HA’ , stream=True).raw)
image = image.resize((300,150))
image.save(‘sample.png’)
image

it becomes a unidentifiedimageerror dont know how to fix this
can anyone have any idea

Answered By: bhuvana