Skip to content

Instantly share code, notes, and snippets.

@mrichman
Last active June 5, 2017 11:29
Show Gist options
  • Save mrichman/ecd32b7f0d87cad807ba2bba7b04bc40 to your computer and use it in GitHub Desktop.
Save mrichman/ecd32b7f0d87cad807ba2bba7b04bc40 to your computer and use it in GitHub Desktop.
Resize JPEG image in AWS S3
package main
import (
"bytes"
"os"
"path"
"image/jpeg"
log "github.com/Sirupsen/logrus"
"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() {
if len(os.Args) != 3 {
log.Fatalf("Bucket name and key required\nUsage: %s bucket_name key", os.Args[0])
}
bucket := os.Args[1]
key := os.Args[2]
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
log.Infof("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.Fatalf("Could not download from S3: %v", err)
}
log.Infof("Decoding image")
imageBytes := buff.Bytes()
reader := bytes.NewReader(imageBytes)
img, err := jpeg.Decode(reader)
if err != nil {
log.Fatalf("bad response: %s", err)
}
log.Infof("Generating thumbnail")
thumbnail := resize.Thumbnail(150, 150, img, resize.Lanczos3)
log.Infof("Encoding image for upload to S3")
buf := new(bytes.Buffer)
err = jpeg.Encode(buf, thumbnail, nil)
if err != nil {
log.Fatalf("JPEG encoding error: %v", err)
}
// Set filename "filename-thumb.jpg"
ext := path.Ext(key)
thumbkey := key[0:len(key)-len(ext)] + "-thumb.jpg"
log.Infof("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.Fatalln("Failed to upload", err)
}
log.Println("Successfully uploaded to", result.Location)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment