图像无法使用 python 图像库打开 [英] Image does not open with python imaging library
问题描述
我刚刚安装了 Python 镜像库并开始学习它,但我无法打开图像文件.
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()
图像属性打印得很好,但是当图像在 Windows 查看器中打开时,我收到错误
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'
我已将文件 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.
推荐答案
使用绝对路径.您可以获取脚本的路径以创建该路径:
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.
__file__
变量是当前模块的文件名,os.path
调用确保它是一个完整的绝对路径(所以在 Windows 上包括驱动器,启动在 POSIX 系统上使用 /
),然后我们只从中取出目录部分.
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.
这篇关于图像无法使用 python 图像库打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!