-
Notifications
You must be signed in to change notification settings - Fork 10
/
image.go
82 lines (76 loc) · 1.97 KB
/
image.go
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package images4
import (
"image"
"image/color"
_ "image/gif"
"image/jpeg"
"image/png"
"log"
"os"
)
// Open opens and decodes an image file for a given path.
func Open(path string) (img image.Image, err error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err = image.Decode(file)
if err != nil {
return nil, err
}
return img, err
}
// ResizeByNearest resizes an image to the destination size
// with the nearest neighbour method. It also returns the source
// image size.
func ResizeByNearest(
src image.Image, dstSize image.Point) (
dst image.RGBA, srcSize image.Point) {
// Original image size.
xMax, xMin := src.Bounds().Max.X, src.Bounds().Min.X
yMax, yMin := src.Bounds().Max.Y, src.Bounds().Min.Y
srcX := xMax - xMin
srcY := yMax - yMin
xScale := float64(srcX) / float64(dstSize.X)
yScale := float64(srcY) / float64(dstSize.Y)
// Destination rectangle.
outRect := image.Rectangle{
image.Point{0, 0}, image.Point{dstSize.X, dstSize.Y}}
// Color model of uint8 per color.
dst = *image.NewRGBA(outRect)
var (
r, g, b, a uint32
)
for y := 0; y < dstSize.Y; y++ {
for x := 0; x < dstSize.X; x++ {
r, g, b, a = src.At(
int(float64(x)*xScale)+xMin,
int(float64(y)*yScale)+yMin).RGBA()
dst.Set(x, y, color.RGBA{
uint8(r >> 8),
uint8(g >> 8),
uint8(b >> 8),
uint8(a >> 8)})
}
}
return dst, image.Point{srcX, srcY}
}
// SaveToPNG encodes and saves image.RGBA to a file.
func SaveToPNG(img *image.RGBA, path string) {
if destFile, err := os.Create(path); err != nil {
log.Println("Cannot create file: ", path, err)
} else {
defer destFile.Close()
png.Encode(destFile, img)
}
}
// SaveToJPG encodes and saves image.RGBA to a file.
func SaveToJPG(img *image.RGBA, path string, quality int) {
if destFile, err := os.Create(path); err != nil {
log.Println("Cannot create file: ", path, err)
} else {
defer destFile.Close()
jpeg.Encode(destFile, img, &jpeg.Options{Quality: quality})
}
}