-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_formats.go
65 lines (57 loc) · 1.6 KB
/
image_formats.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
package streamdeck
import (
"bytes"
"image"
"image/jpeg"
"golang.org/x/image/draw"
)
// toBMP returns the raw bytes of the given image in BMP format.
func toBMP(img image.Image) ([]byte, error) {
rgba := toRGBA(img)
// this is a BMP file header followed by a BPM bitmap info header
// find more information here: https://en.wikipedia.org/wiki/BMP_file_format
header := []byte{
0x42, 0x4d, 0xf6, 0x3c, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00,
0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x48, 0x00,
0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0xc0, 0x3c, 0x00, 0x00, 0xc4, 0x0e,
0x00, 0x00, 0xc4, 0x0e, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}
buffer := make([]byte, len(header)+rgba.Bounds().Dx()*rgba.Bounds().Dy()*3)
copy(buffer, header)
i := len(header)
for y := 0; y < rgba.Bounds().Dy(); y++ {
for x := 0; x < rgba.Bounds().Dx(); x++ {
c := rgba.RGBAAt(x, y)
buffer[i] = c.B
buffer[i+1] = c.G
buffer[i+2] = c.R
i += 3
}
}
return buffer, nil
}
// toJPEG returns the raw bytes of the given image in JPEG format.
func toJPEG(img image.Image) ([]byte, error) {
buffer := bytes.NewBuffer([]byte{})
opts := jpeg.Options{
Quality: 100,
}
err := jpeg.Encode(buffer, img, &opts)
if err != nil {
return nil, err
}
return buffer.Bytes(), err
}
// toRGBA converts an image.Image to an image.RGBA.
func toRGBA(img image.Image) *image.RGBA {
switch img := img.(type) {
case *image.RGBA:
return img
}
out := image.NewRGBA(img.Bounds())
draw.Copy(out, image.Pt(0, 0), img, img.Bounds(), draw.Src, nil)
return out
}