gpt4 book ai didi

python-3.x - 如何将 s3 图像响应读取为对象

转载 作者:行者123 更新时间:2023-12-04 17:38:13 24 4
gpt4 key购买 nike

我在尝试将 s3 响应转换为 b64data 时收到 ValueError: embedded null byte

我用 urllib.request 包尝试过同样的 ValueError: embedded null byte 被抛出


s3_response_object = settings.S3_CLIENT.get_object(Bucket=settings.BUCKET_NAME, Key='image_name.png')
object_content = s3_response_object['Body'].read()
with open(object_content, 'rb') as img:
b64_image = base64.b64encode(img.read())

这是使用预签名 URL 尝试的其他代码

signed_uri = settings.S3_CLIENT. \
generate_presigned_url(ClientMethod='get_object',
Params={'Bucket':settings.BUCKET_NAME,
'Key': 'image_name.png'})
contents = urllib.request.urlopen(signed_uri).read()
with open(contents, "rb") as image_file:
b64_image = base64.b64encode(image_file.read())

两种方法都会抛出这个错误

    with open(object_content, 'rb') as img:
ValueError: embedded null byte

但是使用预签名的 URI 我可以打开图像,但是需要图像作为 b64data。

最佳答案

您不必调用 .read() 两次。object_content 的类型是字节

做类似的事情:

signed_uri = settings.S3_CLIENT. \
generate_presigned_url(ClientMethod='get_object',
Params={'Bucket':settings.BUCKET_NAME,
'Key': 'image_name.png'})
contents = urllib.request.urlopen(signed_uri).read()
b64_img = base64.b64encode(contents)

关于python-3.x - 如何将 s3 图像响应读取为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55689422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com