gpt4 book ai didi

Python urllib2 图像失真

转载 作者:行者123 更新时间:2023-11-28 21:59:18 25 4
gpt4 key购买 nike

我正在使用网站 http://placekitten.com 制作程序,但我遇到了一些问题。使用这个:

im = urllib2.urlopen(url).read()
f = open('kitten.jpeg', 'w')
f.write(im)
f.close()

图像因颜色不匹配而扭曲,如下所示:

http://imgur.com/zVg64Kn.jpeg

我想知道是否有替代方法来使用 urllib2 提取图像。如果有人能提供帮助,那就太好了!

最佳答案

您需要以二进制模式打开文件:

f = open('kitten.jpeg', 'wb')

否则 Python 会将行结尾转换为 native 平台形式,这是一种破坏二进制数据的转换,如 open() function 中所述。 :

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability.

将数据从 URL 复制到文件时,您可以使用 shutil.copyfileob()有效地处理流:

from shutil import copyfileobj

im = urllib2.urlopen(url)
with open('kitten.jpeg', 'wb') as out:
copyfileobj(im, out)

这将以 block 的形式读取数据,避免用大块二进制数据填充内存。 with 语句为您处理关闭文件对象。

关于Python urllib2 图像失真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16877900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com