打开图像错误 Python

2 投票
1 回答
1437 浏览
提问于 2025-04-17 15:38

大家好,我正在尝试打开一个我通过链接下载的图片。我在网站上搜索了一下,找到了一些很有用的东西,并把它们应用到了我的代码中。

*if* __name__ == "__main__":
    import urllib
    droste = urllib.urlopen("http://is.gd/cHqT")
    with open("droste.png", "wb") as imgFile:
        imgFile.write(droste.read())
    print "Got it!"
    droste = Image.open("droste.png")
    while droste:
        droste.show()
        droste = reveal(droste)
        if droste:
            open("droste.png", "wb").write(droste)
            droste = Image.open("droste.png")

错误发生在第七行 "droste = Image.open("droste.png")"。我收到一个错误提示:IOError: 无法识别图片文件。我知道图片已经下载,因为代码在那一行之前运行得很好,而且那行 print "Got it!" 也确认了它已经下载。我不确定我是否需要在打开文件时指定图片文件的路径,而不是仅仅用图片的名字。或者我可能需要检查一下文件的路径。请帮帮我。

1 个回答

2

你的代码是可以运行的,问题出在你怎么运行它。你在评论里提到你在使用PythonAnywhere。PythonAnywhere并不支持图形界面操作。它会把图片下载到正确的文件夹里,但PIL(Python图像库)在PythonAnywhere上无法正常工作。

你可以试试下面的代码来测试一下。

import urllib

if __name__ == "__main__":
    droste = urllib.urlopen("http://is.gd/cHqT")
    with open("droste.png", "wb") as imgFile:
        imgFile.write(droste.read())
    print "Got it!"

    print "Now lets test if it really exists..."
    try:
        with open("droste.png", "rb") as imgFile:
            pass
        print "There were no errors so the file exists"
    except:
        print "ERROR: image was not saved properly!"

如果你在PythonAnywhere上启动一个BASH会话,你会看到文件droste.png存在,你可以把它下载到你的电脑上查看。你的程序是没问题的。

如果你真的想用你的程序,或者想认真学习Python编程,建议你在自己的电脑上安装Python。如果你想把代码保存在云端,可以使用Dropbox、GitHub或Bitbucket。PythonAnywhere有它的用途,但通常情况下,你还是希望在自己的电脑上使用Python。

撰写回答