/
image.go
88 lines (74 loc) · 1.44 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
package macaco
import (
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"strings"
"github.com/rainycape/otto"
)
type _image struct {
image.Image
format string
}
func (i *_image) Width() int {
return i.Bounds().Dx()
}
func (i *_image) Height() int {
return i.Bounds().Dy()
}
func (i *_image) Format() string {
return i.format
}
type info struct {
cfg image.Config
format string
}
func (i *info) Width() int {
return i.cfg.Width
}
func (i *info) Height() int {
return i.cfg.Height
}
func (i *info) Format() string {
return i.format
}
func imageReader(call otto.FunctionCall) (io.Reader, error) {
return strings.NewReader(call.Argument(0).String()), nil
}
func decodeImage(call otto.FunctionCall) otto.Value {
r, err := imageReader(call)
if err != nil {
panic(err)
}
im, format, err := image.Decode(r)
if err != nil {
panic(err)
}
v, err := call.Otto.ToValue(&_image{im, strings.ToUpper(format)})
if err != nil {
panic(err)
}
return v
}
func decodeImageInfo(call otto.FunctionCall) otto.Value {
r, err := imageReader(call)
if err != nil {
panic(err)
}
cfg, format, err := image.DecodeConfig(r)
if err != nil {
panic(err)
}
v, err := call.Otto.ToValue(&info{cfg, strings.ToUpper(format)})
if err != nil {
panic(err)
}
return v
}
func (c *Context) loadImage(obj *otto.Object) {
imageObj := c.newMacacoObject("image")
imageObj.Set("decode", decodeImage)
imageObj.Set("decodeInfo", decodeImageInfo)
}