Get File uploaded to AWS S3 bucket and read into Pillow to convert it

  Kiến thức lập trình

I have a Lambda Function which triggers when a file is uploaded to it’s bucket. I want to
open said file with Pillow and convert it tp JPEG.
Code looks like this:

import os
import json
import boto3
from io import BytesIO
from PIL import Image
import tempfile

s3 = boto3.client('s3')

def lambda_handler(event, context):

if event:
        # Read bucketname, filename from event record
        file_obj = event["Records"][0]
        bucketname = file_obj['s3']['bucket']['name']
        filename = file_obj['s3']['object']['key']

with tempfile.TemporaryFile() as data:
    s3.download_fileobj(bucketname,filename,data)
    data.seek(0)
    im = Image.open(data)
    im.save(out_filename, "JPEG", quality=100)
    s3_out = boto3.resource("s3")
    s3_out.meta.client.upload_file("/",out_bucket,out_filename)
    
return {
    'statusCode':200,
    'body':json.dumps('file was created in /' + out_filename)

The error I get when the function runs is:

[ERROR] UnidentifiedImageError: cannot identify image file <_io.BufferedRandom name=5>
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 45, in lambda_handler
    im = Image.open(data)
  File "/opt/python/lib/python3.8/site-packages/PIL/Image.py", line 3498, in open
    raise UnidentifiedImageError(msg)

I have also tried something like this:

if event:
    bucket = s3.Bucket(bucketname)
    image = bucket.Object(filename)
    img_data = image.get().get('Body').read()
    im = Image.open(BytesIO(img_data))

But get the following error:

Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 35, in lambda_handler
    im = Image.open(BytesIO(img_data))
  File "/opt/python/lib/python3.8/site-packages/PIL/Image.py", line 3498, in open
    raise UnidentifiedImageError(msg)

Not sure how to get Pillow to open this as a file or as raw image data…

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT