-
Notifications
You must be signed in to change notification settings - Fork 28
/
generate.go
102 lines (85 loc) · 2.2 KB
/
generate.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
package winicon
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"image"
"image/png"
"io"
"github.com/energye/energy/v2/pkgs/winicon/internal/winicon"
"golang.org/x/image/draw"
)
// GenerateIcon reads image data from the given reader and generates
// a .ico file that is written to the given writer. The .ico file will include
// a number of icons at the sizes given.
func GenerateIcon(r io.Reader, w io.Writer, sizes []int) error {
header := &winicon.IconFileHeader{
ImageType: 1,
ImageCount: uint16(len(sizes)),
}
iconheaders := make([]winicon.IconHeader, len(sizes))
var imageData bytes.Buffer
// Decode to internal image
imagedata, _, err := image.Decode(r)
if err != nil {
return err
}
// Loop over sizes desired
for index, size := range sizes {
// Check target size
if size == 0 {
return fmt.Errorf("a size of 0 is not valid")
}
// Scale image
rect := image.Rect(0, 0, size, size)
rawdata := image.NewRGBA(rect)
scale := draw.CatmullRom
scale.Scale(rawdata, rect, imagedata, imagedata.Bounds(), draw.Over, nil)
// Convert back to PNG
icondata := new(bytes.Buffer)
writer := bufio.NewWriter(icondata)
err = png.Encode(writer, rawdata)
if err != nil {
return err
}
err = writer.Flush()
if err != nil {
return err
}
// Save image data
imageData.Write(icondata.Bytes())
// Save header information
if size >= 256 {
size = 0
}
iconheaders[index].Width = (uint8)(size)
iconheaders[index].Height = (uint8)(size)
iconheaders[index].BitsPerPixel = 32
iconheaders[index].Size = uint32(len(icondata.Bytes()))
}
// Update the offsets. Start by skipping header+icon headers
var currentOffset uint32 = (uint32)(6 + (16 * len(iconheaders)))
for index := range iconheaders {
iconheaders[index].Offset = currentOffset
currentOffset += iconheaders[index].Size
}
// Write out the header
err = binary.Write(w, binary.LittleEndian, header)
if err != nil {
return err
}
// Write out the icon headers
for _, iconheader := range iconheaders {
err = binary.Write(w, binary.LittleEndian, iconheader)
if err != nil {
return err
}
}
// Write out the image data
_, err = w.Write(imageData.Bytes())
if err != nil {
return err
}
return nil
}