Repository navigation
Expand file tree
/
Copy paththumb.go
More file actions
103 lines (89 loc) · 2.2 KB
/
Copy paththumb.go
File metadata and controls
103 lines (89 loc) · 2.2 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"github.com/nfnt/resize"
"image"
"log"
"os"
)
type Img interface {
HasDesiredDimension() bool
Height() int
Width() int
SetHeight(h int)
SetWidth(w int)
SetDimension() error
DecodeIt() (image.Image, error)
}
type Thumb struct {
width int
height int
desired_width int
desired_height int
img_name string
}
//NewThumb return a new Thumb struct that satisfy the Img interface{
func NewThumb(thumb_width int, thumb_height int, img_name string) Img {
return &Thumb{
desired_width: thumb_width,
desired_height: thumb_height,
img_name: img_name,
}
}
// SetDimension call image.Decodeconfig to read the real dimension of the image
// and set Thumb.widht and Thumb.height
func (t *Thumb) SetDimension() error {
img_file, err := os.Open(t.img_name)
defer img_file.Close()
if err != nil {
log.Printf("the image can not be opened: %v", err)
return err
}
config, _, err := image.DecodeConfig(img_file)
if err != nil {
log.Printf("the image %s can not be decoded: %v", t.img_name, err)
return err
}
t.SetHeight(config.Height)
t.SetWidth(config.Width)
return err
}
// DecodeIt open the image, resize it if necessary, call image.Decode and return an image.Image interface
func (t *Thumb) DecodeIt() (image.Image, error) {
img_file, err := os.Open(t.img_name)
defer img_file.Close()
if err != nil {
log.Printf("the image can not be opened: %v", err)
return nil, err
}
img, _, err := image.Decode(img_file)
if err != nil {
log.Printf("that image can not be decoded: %v", err)
return nil, err
}
if t.HasDesiredDimension() {
return img, nil
} else {
m := resize.Resize(uint(t.desired_width), uint(t.desired_height), img, resize.NearestNeighbor)
return m, nil
}
}
func (t *Thumb) Width() int {
return t.width
}
func (t *Thumb) Height() int {
return t.height
}
func (t *Thumb) SetWidth(width int) {
t.width = width
}
func (t *Thumb) SetHeight(height int) {
t.height = height
}
// HasDesiredDimension returns true if the real dimension of the thumb are equals to the desidered one
func (t *Thumb) HasDesiredDimension() bool {
if t.desired_width == t.width && t.desired_height == t.height {
return true
} else {
return false
}
}