-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase64img.go
111 lines (90 loc) · 2.25 KB
/
base64img.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
111
package main
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"os"
"regexp"
"strings"
)
func main() {
if len(os.Args) < 3 {
PrintUsage()
os.Exit(1)
}
action := os.Args[1]
filename := os.Args[2]
switch action {
case "encode":
encode(filename)
case "decode":
decode(filename)
default:
PrintUsage()
os.Exit(1)
}
}
func PrintUsage() {
os.Stderr.WriteString("base64img\n")
os.Stderr.WriteString("Encodes/Decodes images to/from base64 format\n\n")
os.Stderr.WriteString("Usage:\n")
os.Stderr.WriteString("base64img action filename\n\n")
os.Stderr.WriteString("action can be either encode or decode\n")
os.Stderr.WriteString("filename, in case of encode, is a jpg/png image file\n")
os.Stderr.WriteString("filename, in case of decode, is a text file containing \"data:image/png;base64,...\"\n\n")
os.Stderr.WriteString("Output is written to stdout\n")
}
func encode(filename string) {
data, err := getFileContents(filename)
DieOnError(err)
output := base64.StdEncoding.EncodeToString(data)
mime := http.DetectContentType(data)
fmt.Printf("data:%s;base64,%s", mime, output)
}
func decode(filename string) {
rawdata, err := getFileContents(filename)
DieOnError(err)
encdata := string(rawdata)
encdata = strings.Replace(encdata, "\n", "", -1)
data, err := stripMime(encdata)
DieOnError(err)
output, err := base64.StdEncoding.DecodeString(data)
DieOnError(err)
os.Stdout.Write(output)
}
func getFileContents(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, errors.New("Error opening file")
}
info, err := f.Stat()
if err != nil {
return nil, errors.New("Error getting file stats")
}
len := info.Size()
data := make([]byte, len)
n, err := f.Read(data)
if err != nil {
return nil, errors.New("Error reading file")
}
if int64(n) != len {
return nil, errors.New("Could not read entire contents of file")
}
return data, nil
}
func stripMime(combined string) (string, error) {
re := regexp.MustCompile("data:(.*);base64,(.*)")
parts := re.FindStringSubmatch(combined)
if len(parts) < 3 {
return "", errors.New("Invalid base64 input")
}
data := parts[2]
return data, nil
}
func DieOnError(err error) {
if err != nil {
os.Stderr.WriteString(err.Error())
os.Exit(1)
}
}