Last active
August 29, 2015 14:20
-
-
Save fdelbos/63f0e1357f2c27c0223a to your computer and use it in GitHub Desktop.
Resize an image, create a thumbnail, compress and uploads to S3
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" | |
"compress/gzip" | |
"fmt" | |
"github.com/awslabs/aws-sdk-go/aws" | |
"github.com/awslabs/aws-sdk-go/aws/awsutil" | |
"github.com/awslabs/aws-sdk-go/service/s3" | |
"github.com/hyperboloide/pipe" | |
"github.com/nfnt/resize" | |
"image" | |
"image/jpeg" | |
"io" | |
"log" | |
"os" | |
) | |
func zip(r io.Reader, w io.Writer) error { | |
gzw, err := gzip.NewWriterLevel(w, gzip.BestCompression) | |
if err != nil { | |
return err | |
} | |
defer gzw.Close() | |
_, err = io.Copy(gzw, r) | |
return err | |
} | |
func scaleImage(width uint, height uint) func(io.Reader, io.Writer) error { | |
return func(r io.Reader, w io.Writer) error { | |
img, _, err := image.Decode(r) | |
if err != nil { | |
return err | |
} | |
newImage := resize.Thumbnail(width, height, img, resize.Lanczos2) | |
return jpeg.Encode(w, newImage, nil) | |
} | |
} | |
func s3Upload(path string, body bytes.Buffer) { | |
svc := s3.New(&aws.Config{ | |
Region: "eu-west-1", | |
}) | |
params := &s3.PutObjectInput{ | |
Bucket: aws.String("some_bucket"), | |
Key: aws.String(path), | |
Body: bytes.NewReader(body.Bytes()), | |
ContentType: aws.String("image/jpeg"), | |
ContentEncoding: aws.String("gzip"), | |
} | |
resp, err := svc.PutObject(params) | |
if awserr := aws.Error(err); awserr != nil { | |
fmt.Println("Error:", awserr.Code, awserr.Message) | |
} else if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(awsutil.StringValue(resp)) | |
} | |
func main() { | |
// pipe input | |
in, err := os.Open("test.jpg") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer in.Close() | |
// create a new pipe with a io.Reader | |
pImage := pipe.New(in) | |
// scale the image | |
pImage.Push(scaleImage(600, 600)) | |
// create a tee to upload a thumbnail | |
pThumb := pImage.Tee() | |
// scale and compress the thumbnail | |
pThumb.Push(scaleImage(160, 160), zip) | |
// compresss the image | |
pImage.Push(zip) | |
// too bad this s3 package doesn't support stream upload yet... | |
var buffImage bytes.Buffer | |
pImage.To(&buffImage) | |
if err := pImage.Exec(); err != nil { | |
log.Fatal(err) | |
} | |
s3Upload("test.jpg", buffImage) | |
var buffThumb bytes.Buffer | |
pThumb.To(&buffThumb) | |
if err := pThumb.Exec(); err != nil { | |
log.Fatal(err) | |
} | |
s3Upload("[email protected]", buffThumb) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment