userXktape
userXktape

Reputation: 227

Image does not open with python imaging library

I have just installed the Python imaging library and started to learn it but I cannot sem to open the image file.

    import Image
    im = Image.open("Desert.jpg")
    print im.format, im.size, im.mode
    im.show()

the image attributes are printed fine but when the image opens in windows viewer, I get the error

     File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" 
     ,line 325, in RunScript           
     exec codeObject in __main__.__dict__
     File "C:\Users\Hassan\Documents\imtest.py", line 2, in <module>
     im = Image.open('Desert.jpg')
     File "C:\Python27\lib\site-packages\PIL\Image.py", line 1952, in open
     fp = __builtin__.open(fp, "rb")
     IOError: [Errno 2] No such file or directory: 'Desert.jpg' 

I have placed the file Desert.jpg in the same directory where this script is saved.What should I do to open this file.

Upvotes: 0

Views: 13631

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121864

Use an absolute path. You can get the path of the script to create that path:

import os.path

script_dir = os.path.dirname(os.path.abspath(__file__))
im = Image.open(os.path.join(script_dir, 'Desert.jpg'))

Otherwise, relative files (anything without an absolute path) are opened relative to the current working directory, and that depends entirely on how you started the script and your operating system defaults.

The __file__ variable is the filename of the current module, the os.path calls ensure it is a full absolute path (so including the drive when on Windows, starting with a / on POSIX systems), from which we then take just the directory portion.

Upvotes: 4

Related Questions