[英]Python Flask- how can I read the size of an image before uploading it to Amazon s3
如果您對Python Flask
, Boto3
, Pillow
(又名PIL
)有一些經驗,這個問題可能相當簡單。
我正在嘗試從客戶端接收傳入的圖像(僅允許.jpg
, .jpeg
, .tif
,)並且我想在使用Boto3
將圖像上傳到Amazon 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
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上傳的問題,但我無法弄明白。 你能?
提前致謝。
你很接近 - 改變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
請注意在調用S3時調用以seek
和使用BytesIO。 我不能誇大BytesIO
和StringIO
對於做這類事情有多么有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.