我目前正在生成一个图像,需要在不同的步骤中将其编码和解码为 Base64。但是,我总是收到错误编码错误。我尝试在两者之间保存图像,更改编码,但它总是归结为相同的错误。
r2 = base64.b64decode(r.encode("utf-8"), validate=True).decode("utf-8") UnicodeDecodeError: 'utf-8' 编解码器不能 解码位置 0 处的字节 0x89:无效起始字节
这是一个最小的例子:
from PIL import Image
import base64
import io
if __name__ == "__main__":
# Create an image with a blue background
img = Image.new('RGB', (100, 100), color='blue')
# Save the image to a bytes buffer
buf = io.BytesIO()
img.save(buf, format='PNG')
buf.seek(0)
r = str(base64.b64encode(buf.read()).decode('utf-8'))
print(r)
# This operation throws an error and this cannot be changed
r2 = base64.b64decode(r.encode("utf-8"), validate=True).decode("utf-8")
print(r2)
b64decode
正在工作。 它返回原始图像字节。.decode("utf-8")
不是必需的,而是您 UnicodeDecodeError
的结果。decode('utf-8')
您的 buf
也会发生这种情况。 它不是文本,而是二进制图像,因此无法解码为 Unicode。
# Create an image with a blue background
img = Image.new('RGB', (100, 100), color='blue')
# Save the image to a bytes buffer
buf = io.BytesIO()
img.save(buf, format='PNG')
raw_image = buf.getvalue()
b64_image = base64.b64encode(raw_image)
print("base64:", b64_image)
decoded_raw_image = base64.b64decode(b64_image, validate=True)
print("decoded:", decoded_raw_image)
assert decoded_raw_image == raw_image, "decoded image should match the original image"