从S3存储桶下载图像并存储在非本地变量(boto3)中

2024-06-26 00:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从bucket S3下载一个图像并将其存储在变量中,而不是本地pc中,我该怎么做

我正在使用此代码在本地存储:

BUCKET_NAME = 'mybucket' 
KEYFILE = 'myImage.jpg' 

try:
    s3.Bucket(BUCKET_NAME).download_file(KEYFILE, 'myImageInLocal.jpg')          
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise

Tags: 代码name图像s3bucketdownloadjpgtry
2条回答

您可以使用download_fileobj下载到BytesIO变量:

from io import BytesIO

BUCKET_NAME = 'mybucket' 
KEYFILE = 'myImage.jpg' 

s3_file = BytesIO()

try:
    s3.Bucket(BUCKET_NAME).download_fileobj('myImageInLocal.jpg', s3_file)          
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise

也许你可以试试BytesIO()

import io
image_data = io.BytesIO()

在你的试块里

s3.Bucket(BUCKET_NAME).download_file(KEYFILE, image_data)  

因此,image_data是一个变量,它应该以字节格式显示图像

相关问题 更多 >