-
Notifications
You must be signed in to change notification settings - Fork 0
/
flagicon.go
90 lines (76 loc) · 2.25 KB
/
flagicon.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
/*
Package flagicon provides a function to generate flag icons from image files
By default the flag icon will be of size 14x14 pixels; the original image will
be resized to this size, with a 2px border with color #808080.
If the image is not square, flagicon first crops the image (centered at the center
of the image) such that it is square before it resizes the image.
*/
package main
import (
"github.com/alexflint/go-arg"
"github.com/fogleman/gg"
"github.com/nfnt/resize"
"github.com/oliamb/cutter"
"image"
"log"
"math"
)
// resizeImage resizes the base image to a 14x14 square used for the flagicon
// If the base image is not square, resizeImage first crops the image into a
// square shape, centered on the center of the image.
func resizeImage(base image.Image, left bool) image.Image {
if base.Bounds().Dx() != base.Bounds().Dy() {
newHeight := int(math.Min(float64(base.Bounds().Dx()), float64(base.Bounds().Dy())))
if left {
cropped, err := cutter.Crop(base, cutter.Config{
Width: newHeight,
Height: newHeight,
})
if err != nil {
log.Fatal(err)
}
return resizeToThumbnail(cropped)
} else {
cropped, err := cutter.Crop(base, cutter.Config{
Width: newHeight,
Height: newHeight,
Mode: cutter.Centered,
})
if err != nil {
log.Fatal(err)
}
return resizeToThumbnail(cropped)
}
}
return resizeToThumbnail(base)
}
// resizeToThumbnail resizes the base image to a 14x14 square
func resizeToThumbnail(base image.Image) image.Image {
return resize.Thumbnail(uint(14), uint(14), base, resize.Bilinear)
}
func main() {
var args struct {
Input string `arg:"positional" help:"Path to input image file"`
Output string `arg:"-o" help:"Output file name"`
Left bool `arg:"-l" help:"Generate flagicon from left-side of image, rather than the center"`
}
args.Output = "out.png"
args.Left = false
arg.MustParse(&args)
im, err := gg.LoadImage(args.Input)
if err != nil {
log.Fatal(err)
}
image := resizeImage(im, args.Left)
dc := gg.NewContext(14, 14)
// Clip and draw circle image
dc.DrawCircle(7, 7, 7)
dc.Clip()
dc.DrawImageAnchored(image, 7, 7, 0.5, 0.5)
// Draw image border
dc.DrawCircle(7, 7, 7)
dc.SetHexColor("#808080")
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG(args.Output)
}