/
image.go
103 lines (81 loc) · 1.6 KB
/
image.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package common
import (
"flag"
"fmt"
"github.com/disintegration/imaging"
"github.com/hhrutter/pdfcpu/tiff"
"image"
"image/draw"
"io"
"os"
)
var quality *int
type Orientation int
const (
ORIENTATION_0 Orientation = iota
ORIENTATION_90
ORIENTATION_180
ORIENTATION_270
)
type Rotation int
const (
ROTATE_0 Rotation = iota
ROTATE_90
ROTATE_180
ROTATE_270
)
func init() {
quality = flag.Int("jpeg.quality", 80, "JPEG quality")
}
func LoadImage(path string) (img image.Image, err error) {
defer func() {
if err := recover(); err != nil {
img = nil
err = fmt.Errorf("LoadImage failed: %s", path)
}
}()
img, err = imaging.Open(path)
if err == nil {
return img, nil
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
img, err = tiff.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func CopyImage(src image.Image) draw.Image {
b := src.Bounds()
dst := image.NewRGBA(b)
draw.Draw(dst, b, src, b.Min, draw.Src)
return dst
}
func Rotate(source image.Image, rotation Rotation) image.Image {
switch rotation {
case ROTATE_0:
return CopyImage(source)
case ROTATE_90:
return imaging.Rotate90(source)
case ROTATE_180:
return imaging.Rotate180(source)
case ROTATE_270:
return imaging.Rotate270(source)
}
return source
}
func EncodeJpeg(source image.Image, w io.Writer) error {
return imaging.Encode(w, source, imaging.JPEG, imaging.JPEGQuality(*quality))
}
func SaveJpeg(source image.Image, filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return EncodeJpeg(source, f)
}