【问题标题】:Python Flask- how can I read the size of an image before uploading it to Amazon s3Python Flask-如何在将图像上传到 Amazon s3 之前读取图像的大小
【发布时间】:2018-03-03 06:43:44
【问题描述】:

如果您对Python FlaskBoto3Pillow(又名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

这是关键,我可以 (A) 读取图像或 (B) 上传到 s3,但我不能两者都做。从字面上看,注释掉一个或另一个会产生所需的操作,但不能同时使用两者。

我已将范围缩小到上传。我相信在某个地方,file.strea.read() 操作导致 Boto3 上传出现问题,但我无法弄清楚。可以吗?

提前致谢。

【问题讨论】:

  • 您可能已经到了直播的末尾。一旦发生这种情况,从 boto 的角度来看,就没有更多的字节可以发送了。如果文件可以放入内存,您可能想尝试 BytesIO 作为中介 - 它可以让您重置流指针,以便您可以在检查后上传。 docs.python.org/3/library/io.html#binary-i-o
  • @killthrush 很好的建议,这也是我的主要假设。我该如何解决?

标签: python python-3.x amazon-web-services amazon-s3 python-imaging-library


【解决方案1】:

您已经接近了 - 更改 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

注意对seek 的调用以及对 S3 的调用中使用 BytesIO。我不能夸大BytesIOStringIO 对做这种事情的用处!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2017-05-27
    • 2011-09-18
    • 1970-01-01
    • 2019-12-02
    • 2015-12-18
    相关资源
    最近更新 更多