/
grayscale.go
67 lines (59 loc) · 1.52 KB
/
grayscale.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
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/disintegration/imaging"
)
var output = flag.String("type", "", "Output image format ('' == use source format)")
var destination = flag.String("destination", "", "Output image folder")
func main() {
flag.Parse()
if len(*destination) > 0 {
err := os.MkdirAll(*destination, os.ModePerm)
if err != nil {
fmt.Printf("Unable to create destination: %s\n", err)
os.Exit(1)
}
}
extMatch := regexp.MustCompile(`\.[a-zA-Z0-9]+$`)
filelist := flag.Args()
// if len(filelist) == 0 {
// filelist = []string{"./*.*"}
// }
for _, srcArg := range filelist {
srcFilenames, err := filepath.Glob(srcArg)
if err != nil {
log.Printf("Glob error: %s\n", err)
continue
}
for _, srcFilename := range srcFilenames {
fmt.Printf("Processing [%s]... ", srcFilename)
src, err := imaging.Open(srcFilename)
if err != nil {
log.Printf("error: %s\n", err)
continue
}
dest := imaging.Grayscale(src)
extension := *output
if extension == "" {
extension = strings.TrimLeft(filepath.Ext(srcFilename), ".")
}
destFilename := extMatch.ReplaceAllString(srcFilename, "") + fmt.Sprintf("-grayscale.%s", extension)
if len(*destination) > 0 {
_, file := filepath.Split(destFilename)
destFilename = filepath.Join(*destination, file)
}
err = imaging.Save(dest, destFilename)
if err != nil {
log.Printf("error: %s\n", err)
continue
}
fmt.Printf("OK; written to %s\n", destFilename)
}
}
}