[英]UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte. How to fix it
When I run this code I get an error:当我运行此代码时出现错误:
print(data.decode("utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
My code:我的代码:
import http.client
import json
from dotenv import load_dotenv
import os
load_dotenv()
conn = http.client.HTTPSConnection("api.remove.bg")
apikey = os.getenv('apikey')
imageurl = 'https://www.remove.bg/example-hd.jpg'
payload = json.dumps({
"image_file_b64": "",
"image_url": imageurl,
"size": "preview",
"type": "auto",
"type_level": "1",
"format": "auto",
"roi": "0% 0% 100% 100%",
"crop": False,
"crop_margin": "0",
"scale": "original",
"position": "original",
"channels": "rgba",
"add_shadow": False,
"semitransparency": True,
"bg_color": "",
"bg_image_url": ""
})
headers = {
'X-API-Key': apikey,
'Content-Type': 'application/json'
}
conn.request("POST", "/v1.0/removebg", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
How to fix it?如何解决?
I also tried doing this, but it didn't help.我也尝试这样做,但没有帮助。 But the error has changed.
但是错误已经改变了。
if i replace this如果我更换这个
print(data.decode("utf-8"))
with this有了这个
print(data)
According to their API documentation , the response content is the result image.根据他们的API 文档,响应内容是结果图像。 So you shouldn't try to decode it like it was text.
所以你不应该像文本一样尝试解码它。
Just do with open("image.png", "w") as file: file.write(data)
.只需
with open("image.png", "w") as file: file.write(data)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.