2016-10-13 09:25:11 +00:00
|
|
|
package thumbnail
|
|
|
|
|
|
|
|
import (
|
2016-12-05 08:48:48 +00:00
|
|
|
"bytes"
|
2016-10-13 09:25:11 +00:00
|
|
|
"image"
|
2016-12-05 08:48:48 +00:00
|
|
|
"image/jpeg"
|
2016-12-05 06:05:59 +00:00
|
|
|
)
|
2016-10-13 09:25:11 +00:00
|
|
|
|
|
|
|
func (this *Thumbnailer) RenderScaledImage(src image.Image) ([]byte, error) {
|
|
|
|
srcW := src.Bounds().Max.X
|
|
|
|
srcH := src.Bounds().Max.Y
|
|
|
|
destW := 0
|
|
|
|
destH := 0
|
|
|
|
|
|
|
|
if srcW > srcH {
|
2016-12-05 08:48:48 +00:00
|
|
|
destW = this.width
|
|
|
|
destH = this.height * srcH / srcW
|
2016-10-13 09:25:11 +00:00
|
|
|
} else {
|
2016-12-05 08:48:48 +00:00
|
|
|
destW = this.width * srcW / srcH
|
|
|
|
destH = this.height
|
2016-10-13 09:25:11 +00:00
|
|
|
}
|
|
|
|
|
2016-12-05 08:48:48 +00:00
|
|
|
offsetX := (this.width - destW) / 2
|
|
|
|
offsetY := (this.height - destH) / 2
|
2016-10-13 09:25:11 +00:00
|
|
|
|
|
|
|
scaleW := float64(srcW) / float64(destW)
|
|
|
|
scaleH := float64(srcH) / float64(destH)
|
|
|
|
|
2016-12-05 08:48:48 +00:00
|
|
|
dest := image.NewRGBA(image.Rectangle{Max: image.Point{X: this.width, Y: this.height}})
|
2016-10-13 09:25:11 +00:00
|
|
|
|
2016-12-05 08:48:48 +00:00
|
|
|
switch this.sfmt {
|
2016-10-13 09:25:11 +00:00
|
|
|
|
2016-12-05 08:48:48 +00:00
|
|
|
case SCALEFMT_BILINEAR:
|
|
|
|
|
|
|
|
for y := 0; y < destH; y += 1 {
|
|
|
|
for x := 0; x < destW; x += 1 {
|
|
|
|
c00 := src.At(int(float64(x)*scaleW), int(float64(y)*scaleH))
|
|
|
|
c01 := src.At(int((float64(x)+0.5)*scaleW), int(float64(y)*scaleH))
|
|
|
|
c10 := src.At(int(float64(x)*scaleW), int((float64(y)+0.5)*scaleH))
|
|
|
|
c11 := src.At(int((float64(x)+0.5)*scaleW), int((float64(y)+0.5)*scaleH))
|
|
|
|
cBlend := Blend(Blend(c00, c01), Blend(c10, c11))
|
|
|
|
dest.Set(x+offsetX, y+offsetY, cBlend)
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
case SCALEFMT_NN:
|
|
|
|
|
|
|
|
for y := 0; y < destH; y += 1 {
|
|
|
|
for x := 0; x < destW; x += 1 {
|
2016-10-13 09:25:11 +00:00
|
|
|
mapx := int(float64(x) * scaleW)
|
|
|
|
mapy := int(float64(y) * scaleH)
|
|
|
|
dest.Set(x+offsetX, y+offsetY, src.At(mapx, mapy))
|
2016-12-05 08:48:48 +00:00
|
|
|
}
|
|
|
|
}
|
2016-10-13 09:25:11 +00:00
|
|
|
|
2016-12-05 08:48:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
switch this.ofmt {
|
|
|
|
case OUTPUT_PNG_CRUSH:
|
2018-06-04 05:41:07 +00:00
|
|
|
return crushFast(dest)
|
2016-10-13 09:25:11 +00:00
|
|
|
|
2016-12-05 08:48:48 +00:00
|
|
|
case OUTPUT_JPG:
|
|
|
|
buff := bytes.Buffer{}
|
|
|
|
err := jpeg.Encode(&buff, dest, &jpeg.Options{Quality: jpeg.DefaultQuality})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2016-10-13 09:25:11 +00:00
|
|
|
}
|
2016-12-05 08:48:48 +00:00
|
|
|
|
|
|
|
return buff.Bytes(), nil
|
|
|
|
|
|
|
|
default:
|
|
|
|
return nil, ErrInvalidOption
|
|
|
|
|
2016-10-13 09:25:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|