thumbnail/image.go

78 lines
1.6 KiB
Go

package thumbnail
import (
"bytes"
"image"
"image/jpeg"
)
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 {
destW = this.width
destH = this.height * srcH / srcW
} else {
destW = this.width * srcW / srcH
destH = this.height
}
offsetX := (this.width - destW) / 2
offsetY := (this.height - destH) / 2
scaleW := float64(srcW) / float64(destW)
scaleH := float64(srcH) / float64(destH)
dest := image.NewRGBA(image.Rectangle{Max: image.Point{X: this.width, Y: this.height}})
switch this.sfmt {
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 {
mapx := int(float64(x) * scaleW)
mapy := int(float64(y) * scaleH)
dest.Set(x+offsetX, y+offsetY, src.At(mapx, mapy))
}
}
}
switch this.ofmt {
case OUTPUT_PNG_CRUSH:
return crushFast(dest)
case OUTPUT_JPG:
buff := bytes.Buffer{}
err := jpeg.Encode(&buff, dest, &jpeg.Options{Quality: jpeg.DefaultQuality})
if err != nil {
return nil, err
}
return buff.Bytes(), nil
default:
return nil, ErrInvalidOption
}
}