Last active
December 28, 2021 08:20
-
-
Save mrichman/20f5c99809f2f6385b52e4e48360d0b3 to your computer and use it in GitHub Desktop.
AWS Lambda function in Go to resize an image uploaded to S3. Uses https://github.com/apex/apex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"image/jpeg" | |
"log" | |
"path" | |
"strings" | |
apex "github.com/apex/go-apex" | |
apexS3 "github.com/apex/go-apex/s3" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/s3" | |
"github.com/aws/aws-sdk-go/service/s3/s3manager" | |
"github.com/nfnt/resize" | |
) | |
func main() { | |
apexS3.HandleFunc(func(event *apexS3.Event, ctx *apex.Context) error { | |
for _, record := range event.Records { | |
sess := session.New(&aws.Config{Region: aws.String(record.AWSRegion), | |
DisableRestProtocolURICleaning: aws.Bool(true)}) | |
bucket := record.S3.Bucket.Name | |
key := record.S3.Object.Key | |
log.Printf("Bucket: %s", bucket) | |
log.Printf("Key: %s", key) | |
if strings.HasSuffix(key, "thumb.jpg") { | |
continue | |
} | |
log.Printf("Fetching s3://%v/%v", bucket, key) | |
buff := &aws.WriteAtBuffer{} | |
s3dl := s3manager.NewDownloader(sess) | |
_, err := s3dl.Download(buff, &s3.GetObjectInput{ | |
Bucket: aws.String(bucket), | |
Key: aws.String(key), | |
}) | |
if err != nil { | |
log.Printf("Could not download from S3: %v", err) | |
} | |
log.Printf("Decoding image: %v bytes", len(buff.Bytes())) | |
imageBytes := buff.Bytes() | |
reader := bytes.NewReader(imageBytes) | |
img, err := jpeg.Decode(reader) | |
if err != nil { | |
log.Printf("bad response: %s", err) | |
} | |
log.Printf("Generating thumbnail") | |
thumbnail := resize.Thumbnail(150, 150, img, resize.Lanczos3) | |
log.Printf("Encoding image for upload to S3") | |
buf := new(bytes.Buffer) | |
err = jpeg.Encode(buf, thumbnail, nil) | |
if err != nil { | |
log.Printf("JPEG encoding error: %v", err) | |
} | |
// Set filename "filename-thumb.jpg" | |
ext := path.Ext(key) | |
thumbkey := key[0:len(key)-len(ext)] + "-thumb.jpg" | |
log.Printf("Preparing S3 object: %s", thumbkey) | |
uploader := s3manager.NewUploader(sess) | |
result, err := uploader.Upload(&s3manager.UploadInput{ | |
Body: bytes.NewReader(buf.Bytes()), | |
Bucket: aws.String(bucket), | |
Key: aws.String(thumbkey), | |
}) | |
if err != nil { | |
log.Printf("Failed to upload: %v", err) | |
} | |
log.Printf("Successfully uploaded to: %v", result.Location) | |
} | |
return nil | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's very cool, thanks, man.