image - 数据看起来像二进制数据,但以字符串形式返回。如何另存为图片?
问题描述
我正在使用请求模块获取图像数据。返回的数据看起来像这样解释的二进制数据:
`����JFIF��>CREATOR: gd-jpeg v1.0(使用 IJG JPEG v62),默认质量 ��C $。",#(7),01444'9=82<.342��C
2!!
我尝试使用以下方法保存:
image = open("test.jpg", "wb")
image.write(image_data)
image.close()
但这抱怨它需要一个类似字节的对象。我尝试过使用各种格式(如“utf-8”等)执行 result.text.encode(),但无法打开生成的图像文件。我也试过做 bytes(result.text, "utf-8") 和 bytearray(result.text, "utf-8") 和同样的问题。无论如何,我认为这些都大致相同。有人可以帮我将其转换为类似字节的对象而不破坏数据吗?
此外,我在请求中的标头是“image/jpeg”,但它仍将数据作为字符串发送给我。
谢谢!
解决方案
使用该content
字段而不是text
:
import requests
r = requests.get('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png')
with open('test.png', 'wb') as file:
file.write(r.content)
请参阅:https ://requests.readthedocs.io/en/master/user/quickstart/#binary-response-content