【发布时间】:2020-08-17 20:17:11
【问题描述】:
我使用的是 Python 3.8。我想将图像字节数据放入 JSON 对象。所以我尝试了这个
with open(os.path.join(dir_path, "../image_data", "myimg.jpg"), mode='rb') as img_file:
image_data = img_file.read().decode("utf-16")
my_json_data = {
"image_data": image_data
...
}
但是image_data = 行给出了这个错误:
UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 0-1: illegal UTF-16 surrogate
将数据加载到 JSON 对象中的正确方法是什么?
【问题讨论】:
-
可能是因为您正在阅读的图像未编码为 utf-16?
-
图像数据通常是二进制的(由
mode='rb'适当处理)。为什么你认为它是 utf-16? -
你打算如何为 json 文件编码 - 因为 JSON 只是文本,你不需要使用 base64 或类似的编码吗?
标签: python json python-3.x file getimagedata