数据看起来像二进制数据,但 returns 是字符串。如何另存为图片?

Data looks like binary data , but returns as string. How to save as 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()

但这抱怨它需要 bytes-like object。我曾尝试使用“utf-8”等各种格式执行 result.text.encode(),但无法打开生成的图像文件。我也试过做 bytes(result.text, "utf-8") 和 bytearray(result.text, "utf-8") 和同样的问题。无论如何,我认为这些都大致相同。谁能帮我把它转换成 bytes-like object 而不会破坏数据?

此外,我在请求中的 headers 是 '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