我有 s3 路径,其中包含 S3 中的 png/jpeg 图像。我想在 python 运行时将此图像转换为 base64。看来我能做的是,我可以尝试下载图像并将它们编码为 Base64。我想知道是否有更好的方法来使用 boto3 获取编码图像,因为我真的不需要下载它们。
另外,是否可以将 s3 路径与 boto3 一起使用?根据我的研究,这似乎不可能,所以我们需要拆分路径来获取存储桶和对象名称。
由于
boto3
需要做的事情实际上并不需要编码,因此它不提供此选项。您可以自己即时编码内容:
import base64
import io
import boto3
class Base64Encoder(io.IOBase):
def __init__(self, fileobj):
self.fileobj = fileobj
def write(self, b):
return self.fileobj.write(base64.b64encode(b))
# some code that sets things up
...
s3 = boto3.client('s3')
# download from S3, encode to base64 on the fly, and write to wherever you need it
with whatever_gets_your_file_like_target() as f:
s3.download_fileobj('mybucket', 'mykey', Base64Encoder(f))
由于您没有提供有关实际需要在何处编写 Base64 编码内容的信息,因此我只是在此处调用
whatever_gets_your_file_like_target()
。