-
Notifications
You must be signed in to change notification settings - Fork 263
/
image.go
43 lines (39 loc) · 923 Bytes
/
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
package main
import (
"bytes"
"image"
"image/png"
)
// Image converts an image.Image to DisplayData containing PNG []byte,
// or to DisplayData containing error if the conversion fails
func Image(img image.Image) Data {
bytes, mimeType, err := encodePng(img)
if err != nil {
return makeDataErr(err)
}
return Data{
Data: MIMEMap{
mimeType: bytes,
},
Metadata: MIMEMap{
mimeType: imageMetadata(img),
},
}
}
// encodePng converts an image.Image to PNG []byte
func encodePng(img image.Image) (data []byte, mimeType string, err error) {
var buf bytes.Buffer
err = png.Encode(&buf, img)
if err != nil {
return nil, "", err
}
return buf.Bytes(), MIMETypePNG, nil
}
// imageMetadata returns image size, represented as MIMEMap{"width": width, "height": height}
func imageMetadata(img image.Image) MIMEMap {
rect := img.Bounds()
return MIMEMap{
"width": rect.Dx(),
"height": rect.Dy(),
}
}