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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
package main
import (
"errors"
"flag"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"os"
"strings"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
)
func load(filename string) (image.Image, error) {
file := os.Stdin
if filename != "-" {
var err error
file, err = os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
}
img, _, err := image.Decode(file)
if err != nil {
return nil, fmt.Errorf("decode %q: %s", filename, err)
}
return img, nil
}
func run() error {
args := flag.Args()
if len(args) != 2 {
return errors.New("usage: convert input-file output-file")
}
inputFileName, outputFileName := args[0], args[1]
n := strings.LastIndex(outputFileName, ".")
if n < 0 {
return errors.New("unknown output file extension")
}
ext := outputFileName[n+1:]
switch ext {
case "gif", "jpeg", "jpg", "png", "bmp", "tiff":
default:
return fmt.Errorf("unknown output file extension %q", ext)
}
input, err := load(inputFileName)
if err != nil {
return err
}
outputFile, err := os.Create(outputFileName)
if err != nil {
return err
}
defer outputFile.Close()
switch ext {
case "gif":
err = gif.Encode(outputFile, input, nil)
case "jpeg", "jpg":
err = jpeg.Encode(outputFile, input, nil)
case "png":
err = png.Encode(outputFile, input)
case "bmp":
err = bmp.Encode(outputFile, input)
case "tiff":
err = tiff.Encode(outputFile, input, nil)
}
if err != nil {
return err
}
return outputFile.Close()
}
func main() {
flag.Usage = func() {
fmt.Fprint(os.Stderr, `Usage: convert input-file output-file
Supported formats:
png
jpeg
bmp
tiff
webp (input only)
`)
}
flag.Parse()
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "convert: %s\n", err)
os.Exit(1)
}
}
|