This question might be fairly straightforward, if you have some experience with Python Flask
, Boto3
, Pillow
(aka PIL
).
I'm attempting to receive an incoming image from a client (only allowing .jpg
, .jpeg
, .tif
,) and i'd like to read the dimensions of the image before uploading it to Amazon S3 using Boto3
.
The code is fairly straight forward:
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
Here's the catch, I can either (A) read the image OR (B) upload to s3, but I can't do both. Literally, commenting out one or the other produces the desired operation, but not both in combination.
I've narrowed it down to the upload. It's my belief that somewhere along the line, the file.strea.read() operation is causing an issue with the Boto3 upload, but I can't figure it out. Can you?
Thanks in advance.
You're close - changing the byte source for S3 should do it. Roughly, something like this:
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
Note the call to seek
and the use of BytesIO in the call to S3. I can't overstate how useful BytesIO
and StringIO
are for doing this sort of thing!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.