ach*_*chi 4 python amazon-s3 amazon-web-services python-imaging-library python-3.x
这个问题可能是非常简单的,如果你有一些经验Python Flask,Boto3,Pillow(又名PIL)。
我试图从客户端(仅允许接收传入图像.jpg,.jpeg,.tif,),我想使用它上传到Amazon S3之前,读取的图像的尺寸Boto3。
该代码相当简单:
file = request.files['file']
# produces an instance of FileStorage
asset = models.Asset(file, AssetType.profile_img, donor.id)
# a model managed by the ORM
img = Image.open(BytesIO(file.stream.read()))
# produces a PIL Image object
size = img.size
# read the size of the Image object
asset.width = size[0]
asset.height = size[1]
# set the size to the ORM
response = s3.Object('my-bucket', asset.s3_key()).put(Body=file)
# upload to S3
Run Code Online (Sandbox Code Playgroud)
这很重要,我可以(A)读取图像,或者(B)上传到s3,但我不能两者都做。从字面上看,注释掉一个或另一个会产生所需的操作,但不能两者结合在一起。
我已将其范围缩小到上传。我相信,file.strea.read()操作会导致Boto3上传出现问题,但我无法弄清楚。你是否可以?
提前致谢。
您快接近了-更改S3的字节源就可以了。大概是这样的:
file = request.files['file']
# produces an instance of FileStorage
asset = models.Asset(file, AssetType.profile_img, donor.id)
# a model managed by the ORM
image_bytes = BytesIO(file.stream.read())
# save bytes in a buffer
img = Image.open(image_bytes)
# produces a PIL Image object
size = img.size
# read the size of the Image object
asset.width = size[0]
asset.height = size[1]
# set the size to the ORM
image_bytes.seek(0)
response = s3.Object('my-bucket', asset.s3_key()).put(Body=image_bytes)
# upload to S3
Run Code Online (Sandbox Code Playgroud)
请注意seek对S3 的调用和对BytesIO的使用。我不能高估这样做的作用BytesIO和意义StringIO!
| 归档时间: |
|
| 查看次数: |
928 次 |
| 最近记录: |