-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
media.go
95 lines (84 loc) · 1.93 KB
/
media.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
package gouse
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"log"
"os"
)
/* Canvas */
func CreateCanvas(size int, hexColor string) (*image.RGBA, error) {
width, height := size, size
bgColor, err := HexToRGBA(hexColor)
if err != nil {
log.Fatal(err)
}
background := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(background, background.Bounds(), &image.Uniform{C: bgColor},
image.Point{}, draw.Src)
return background, err
}
/* Convert */
func HexToRGBA(hex string) (color.RGBA, error) {
var (
rgba color.RGBA
err error
errInvalidFormat = fmt.Errorf("invalid")
)
rgba.A = 0xff
if hex[0] != '#' {
return rgba, errInvalidFormat
}
hexToByte := func(b byte) byte {
switch {
case b >= '0' && b <= '9':
return b - '0'
case b >= 'a' && b <= 'f':
return b - 'a' + 10
case b >= 'A' && b <= 'F':
return b - 'A' + 10
}
err = errInvalidFormat
return 0
}
switch len(hex) {
case 7:
rgba.R = hexToByte(hex[1])<<4 + hexToByte(hex[2])
rgba.G = hexToByte(hex[3])<<4 + hexToByte(hex[4])
rgba.B = hexToByte(hex[5])<<4 + hexToByte(hex[6])
case 4:
rgba.R = hexToByte(hex[1]) * 17
rgba.G = hexToByte(hex[2]) * 17
rgba.B = hexToByte(hex[3]) * 17
default:
err = errInvalidFormat
}
return rgba, err
}
func formatError(message string, err error) error {
return fmt.Errorf("%s: %v", message, err)
}
func PNGToJPG(input, output string) error {
pngFile, err := os.Open(input)
if err != nil {
return formatError("Error opening PNG file", err)
}
defer pngFile.Close()
pngImage, err := png.Decode(pngFile)
if err != nil {
return formatError("Error decoding PNG file", err)
}
jpegFile, err := os.Create(output)
if err != nil {
return formatError("Error creating JPEG file", err)
}
defer jpegFile.Close()
err = jpeg.Encode(jpegFile, pngImage, nil)
if err != nil {
return formatError("Error encoding image to JPEG", err)
}
return nil
}