使用 Python 下载的图像已损坏?

Images downloaded with Python are corrupted?

我尝试下载图像,但由于某种原因它们损坏了?例如:这是我要得到的一张图片。

结果是这样的

我的测试代码是:

import urllib2

def download_web_image(url):
    request = urllib2.Request(url)
    img = urllib2.urlopen(request).read()
    with open ('test.jpg', 'w') as f: f.write(img)

download_web_image("http://upload.wikimedia.org/wikipedia/commons/8/8c/JPEG_example_JPG_RIP_025.jpg")

为什么会这样,我该如何解决?

您正在以默认(文本)模式打开 'test.jpg' 文件,这导致 Python 在 Windows 上使用 "correct" 换行符:

In text mode, the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n. When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings.

当然,JPEG 文件不是文本文件,'fixing'换行只会损坏图像。相反,以二进制模式打开文件:

with open('test.jpg', 'wb') as f:
    f.write(img)

有关详细信息,请参阅 documentation