-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresizer.go
66 lines (58 loc) · 1.37 KB
/
resizer.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
package main
import (
"fmt"
"image"
"image/jpeg"
"log/slog"
"os"
)
func writeNewImg(img *image.Image, scale int, filename string) error {
// create destination file
dstFile, err := os.Create(fmt.Sprintf("%s-%d.jpeg", filename, scale))
if err != nil {
return err
}
defer dstFile.Close()
// create new image
maxX := (*img).Bounds().Dx() / scale
maxY := (*img).Bounds().Dy() / scale
// newImg := image.NewRGBA((*img).Bounds())
newImg := image.NewRGBA(image.Rect(0, 0, maxX, maxY))
fmt.Printf("New image bounds: %v\n", newImg.Bounds())
for y := range (*newImg).Bounds().Dy() {
for x := range (*newImg).Bounds().Dx() {
newImg.Set(x, y, (*img).At(x*scale, y*scale))
}
}
err = jpeg.Encode(dstFile, newImg, nil)
if err != nil {
slog.Error("Error encoding new jpeg image")
return err
}
return nil
}
func createAltSizes(srcPath string) {
slog.Info(fmt.Sprintf("Creating alt sizes for %s", srcPath))
srcFile, err := os.Open(srcPath)
if err != nil {
slog.Error("Error opening file")
panic(err)
}
defer srcFile.Close()
img, err := jpeg.Decode(srcFile)
if err != nil {
slog.Error("Error decoding image")
panic(err)
}
filename := srcFile.Name()
// Create medium img at 1/4 size
err = writeNewImg(&img, 4, filename)
if err != nil {
panic(err)
}
// Create icon image at 1/10 size
err = writeNewImg(&img, 10, filename)
if err != nil {
panic(err)
}
}