forked from lalluviamola/web-blog
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptimize_images.go
More file actions
83 lines (75 loc) · 1.91 KB
/
optimize_images.go
File metadata and controls
83 lines (75 loc) · 1.91 KB
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
83
package main
import (
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"github.com/kjk/common/u"
)
func optimizeImages(dirs ...string) {
var (
sem = make(chan bool, runtime.NumCPU()+1)
wg sync.WaitGroup
nProcessed int
nOptimized int
imgoptSizeBefore int64
sizeAFter int64
imgoptMu sync.Mutex
)
optimizeWithOptipng := func(path string) {
logf(ctx(), "Optimizing '%s'\n", path)
sizeBefore := u.FileSize(path)
cmd := exec.Command("optipng", "-o5", path)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
// it's ok if fails. some jpeg images are saved as .png
// which trips it
logf(ctx(), "optipng failed with '%s'\n", err)
}
sizeAfter := u.FileSize(path)
panicIf(sizeBefore == -1 || sizeAfter == -1)
imgoptMu.Lock()
defer imgoptMu.Unlock()
nProcessed++
if sizeBefore != sizeAfter {
nOptimized++
}
sizeAFter += sizeAfter
imgoptSizeBefore += sizeBefore
}
maybeOptimizeImage := func(path string) {
ext := filepath.Ext(path)
ext = strings.ToLower(ext)
switch ext {
// TODO: for .gif requires -snip
case ".png", ".tiff", ".tif", "bmp":
wg.Add(1)
// run optipng in parallel
go func() {
sem <- true
optimizeWithOptipng(path)
<-sem
wg.Done()
}()
}
}
// verify we have optipng installed
cmd := exec.Command("optipng", "-h")
err := cmd.Run()
panicIf(err != nil, "optipng is not installed")
for _, dir := range dirs {
filepath.WalkDir(dir, func(path string, e fs.DirEntry, err error) error {
if err == nil && e.Type().IsRegular() {
maybeOptimizeImage(path)
}
return nil
})
}
wg.Wait()
logf(ctx(), "optimizeAllImages: processed %d, optimized %d, %s => %s\n", nProcessed, nOptimized, formatSize(imgoptSizeBefore), formatSize(sizeAFter))
}