如何从包含二进制数据的 str 构建映像?



>我有一个字节字符串,并试图将其转换为文件,但我不断收到错误:

OS Error cannot identify image file <_io.BytesIO object at 0x03BBD330>

我实现的代码如下:

def test_view(request):
with open("test_json.json") as imageFile:
b=bytearray(json.load(imageFile)["IMAGE_DATA"], 'utf8')
print(b)
image = Image.open(io.BytesIO(b))
response = HttpResponse(content_type="image/jpeg")
image.save(response, "JPEG")
return response

字节字符串是从 json 文件中读取的,它看起来像这样,但它要长得多,我只是复制了一些字符。

"b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00\x05\x04\x04\x04\x04\x03\x05\x04\x04\x04\x06\x05\x05\x06\x08\r\x08\x08\x07\x07\x08\x10\x0b\x0c\t\r\x13\x10\x14\x13\x12\x10\x12\x12\x14\x17\x1d\x19\x14\x16\x1c\x16\x12\x12\x1a#\x1a\x1c\x1e\x1f!!!\x14\x19$\'$ &\x1d ! \xff\xdb\x00C\x01\x05\x06\x06\x08\x07\x08\x0f\x08\x08\x0f \x15\x12\x15                                                  \xff\xc0\x00\x11\x08\x01&\x02q\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xc4\x00\x1f\x01\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x11\x00\x02\x01\x02\x04\x04\x03\x04\x07\x05\x04\x04\x00\x01\x02w\x00\x01\x02\x03\x11\x04\x05!1\x06\x12AQ\x07aq\x13"2\x81\x08\x14B\x91\xa1\xb1\xc1\t#3R\xf0\x15br\xd1\n\x16$4\xe1%\xf1\x17\x18\x19\x1a&\'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99'"

我不完全确定这个问题的最佳解决方案是什么,因为您遇到的问题是json.load(imageFile)["IMAGE_DATA"]将返回"b'bytes'",当它转换为字节数组时,您正在做bytearray("b'bytes'"),这是错误的。

此外,此行为在 JSON 解析器之间是特定的,不同的 JSON 解析器可能会有不同的解释

要么剥离包装字节串的b'',要么执行ast.literal_eval()

def test_view(request):
with open("test_json.json") as imageFile:
b = bytearray(
ast.literal_eval(
json.load(imageFile)["IMAGE_DATA"], 'utf8')
print(b)
image = Image.open(io.BytesIO(b))
response = HttpResponse(content_type="image/jpeg")
image.save(response, "JPEG")
return response

最新更新