aboutsummaryrefslogtreecommitdiff
path: root/go/images/resizing.go
blob: f5077c1fde878a3a615f5a4dfd0d9b55baea9954 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package images

import (
	"bytes"
	"github.com/disintegration/imaging"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
)

func Resized(ext string, data []byte, width, height int) (resized []byte) {
	if width == 0 && height == 0 {
		return data
	}
	if srcImage, _, err := image.Decode(bytes.NewReader(data)); err == nil {
		bounds := srcImage.Bounds()
		var dstImage *image.NRGBA
		if width == height && bounds.Dx() != bounds.Dy() {
			dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
		} else {
			dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
		}
		var buf bytes.Buffer
		switch ext {
		case ".png":
			png.Encode(&buf, dstImage)
		case ".jpg":
			jpeg.Encode(&buf, dstImage, nil)
		case ".gif":
			gif.Encode(&buf, dstImage, nil)
		}
		return buf.Bytes()
	}
	return data
}