2

大家好,我正在尝试打开通过链接下载的图像。我在该网站上进行了搜索,发现了一些非常有用的东西并将其实现到我的代码中。

*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")

错误发生在第 7 行"droste = Image.open("droste.png")"。我收到 IOError:无法识别图像文件。我知道图像已被下载,因为代码运行良好,直到该特定行并且该行 print "Got it!" 实际上确认它已被下载。不知道是不是需要在open的参数中指定图片文件的路径,而不是图片名。或者也许我需要检查文件的路径。请帮忙。

4

1 回答 1

2

您的代码可以正常工作。问题是你如何运行它。您在评论中提到您正在使用 PythonAnywhere。PythonAnywhere 未设置为执行任何图形操作。它会将图像下载到正确的目录中,但 PIL 无法在 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。

于 2013-02-12T23:37:55.417 回答