-
Notifications
You must be signed in to change notification settings - Fork 2
/
ricons.go
110 lines (96 loc) · 2.61 KB
/
ricons.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
103
104
105
106
107
108
109
110
// See LICENSE.txt for licensing information.
// Package ricons implements random icon generator framework.
package ricons
import (
"errors"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"sync"
)
const (
VERSION = `0.0.3` // framework version
POOLSIZE = 256 // default image pool size
)
// Format is an enum of available image formats.
type Format string
// EncoderOptions holds encoder options for supported output image formats.
type EncoderOptions struct {
GIF *gif.Options // encoder options for GIF images
JPEG *jpeg.Options // encoder options for JPEG images
}
// Icon holds an icon dimensions and the actual pixel data.
type Icon struct {
Dim image.Rectangle // dimensions
Image *image.RGBA // actual pixel data
EncoderOpts *EncoderOptions // encoder options
}
// Generator describes a minimal Icon generator.
type Generator interface {
NewIcon(width, height int) (*Icon, error) // create, draw and return an Icon
Generate(i *Icon) error // draw into an existing Icon
fmt.Stringer
}
// Implemented image formats.
const (
PNG Format = "png"
GIF Format = "gif"
JPEG Format = "jpeg"
)
// Error variables.
var (
ErrUnknownFormat = errors.New("icon encode: unknown format")
)
// Registry holds a global map of registered Generators.
var Registry = make(map[string]Generator, 0)
var (
mtx sync.Mutex // image pool mutex
imagePool = make(map[image.Rectangle]*pool, 0) // hash of image pools
)
// Register registers a generator at compile time.
// It will panic if you try to overwrite an already existing Generator.
func Register(name string, g Generator) {
if _, exists := Registry[name]; exists {
panic(fmt.Sprintf("generator '%s' already registered", name))
}
Registry[name] = g
}
// Icon returns a basic fully initialised Icon.
// This includes default EncoderOptions.
func NewIcon(width, height int) *Icon {
d := image.Rect(0, 0, width, height)
mtx.Lock()
p, exist := imagePool[d]
if !exist {
p = makePool(width, height, POOLSIZE)
imagePool[d] = p
}
mtx.Unlock()
return &Icon{
Dim: d,
Image: p.get(),
EncoderOpts: &EncoderOptions{
GIF: &gif.Options{NumColors: 256},
JPEG: &jpeg.Options{Quality: 75},
},
}
}
// Encode encodes and writes a given Icon in the given image format.
func (i *Icon) Encode(f Format, o io.Writer) error {
var err error
switch f {
case PNG:
err = png.Encode(o, i.Image)
case GIF:
err = gif.Encode(o, i.Image, i.EncoderOpts.GIF)
case JPEG:
err = jpeg.Encode(o, i.Image, i.EncoderOpts.JPEG)
default:
err = ErrUnknownFormat
}
imagePool[i.Dim].put(i.Image)
return err
}