This article is about how to convert base64 string image to byte and invoke to PIL image.
Then we can handle image whatever we want to ex) image resize ..
base64 image come from
img_base64 = event['base64Image']
and then convert to byte data
imgdata = base64.b64decode(img_base64)
then it can save to image file and load to Image.open(filename)
or
invoke to pil image directly :
img2 = Image.open(io.BytesIO(imgdata))
In the source code, there is also example how to upload image to s3 bucket.
refer to below code.
//
import sys
sys.path.append("/opt")
import json
import boto3
import os
import io
from PIL import Image
import base64
ACCESS_KEY = os.environ.get('ACCESS_KEY')
SECRET_KEY = os.environ.get('SECRET_KEY')
def uploadToS3(bucket, s3_path, local_path):
s3_client = boto3.client(
's3',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
)
s3_client.upload_file(local_path, bucket, s3_path)
def lambda_handler(event, context):
#base64 image string
img_base64 = event['base64Image']
#string to byte
imgdata = base64.b64decode(img_base64)
#save some image file
with open("/tmp/imageToSave.png", "wb") as fh:
fh.write(imgdata)
#open("/tmp/imageToSave.png",'rb')
uploadToS3("input-image1", "imageToSave.png", "/tmp/imageToSave.png")
#load image file to pil
img = Image.open("/tmp/imageToSave.png")
width, height = img.size
#load
img2 = Image.open(io.BytesIO(imgdata))
width2, height2 = img2.size
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello leon it is from Lambda!'),
'width file': width,
'heihgt file' : height,
'width pil': width2,
'heihgt pil' : height2
}
//
These method is referenced by:
https://stackoverflow.com/questions/16214190/how-to-convert-base64-string-to-image
https://stackoverflow.com/questions/11727598/pil-image-open-working-for-some-images-but-not-others
https://stackoverflow.com/questions/16214190/how-to-convert-base64-string-to-image
https://stackoverflow.com/questions/6444548/how-do-i-get-the-picture-size-with-pil
Thanks for effort.