forked from anthonynsimon/bild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
89 lines (76 loc) · 1.71 KB
/
io.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
83
84
85
86
87
88
89
/*Package imgio provides basic image file input/output.*/
package imgio
import (
"image"
"image/jpeg"
"image/png"
"io"
"os"
"path/filepath"
"strings"
)
// Format is used to identify the image encoding type
type Format int
// Supported image encoding types
const (
JPEG = iota
PNG
)
// Open loads and decodes an image from a file and returns it.
//
// Usage example:
// // Encode an image to a writer in PNG format,
// // returns an error if something went wrong
// img, err := Open("exampleName")
//
func Open(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
// Encode writes an image in the specified format.
//
// Usage example:
// // Encode an image to a writer in PNG format,
// // returns an error if something went wrong
// err := Encode(outFile, img, bild.PNG)
//
func Encode(w io.Writer, img image.Image, format Format) error {
var err error
switch format {
case PNG:
err = png.Encode(w, img)
case JPEG:
err = jpeg.Encode(w, img, &jpeg.Options{Quality: 95})
}
return err
}
// Save creates a file and writes to it an image in the specified format
//
// Usage example:
// // Save an image to a file in PNG format,
// // returns an error if something went wrong
// err := Save("exampleName", img, bild.PNG)
//
func Save(filename string, img image.Image, format Format) error {
filename = strings.TrimSuffix(filename, filepath.Ext(filename))
switch format {
case PNG:
filename += ".png"
case JPEG:
filename += ".jpg"
}
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return Encode(f, img, format)
}