-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrobohash.go
334 lines (317 loc) · 8.35 KB
/
robohash.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package gorobohash
import (
"bytes"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"fmt"
"image"
"image/draw"
"image/jpeg"
"image/png"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
_ "image/png"
"github.com/nfnt/resize"
)
//resource define resource path
type resource struct {
bgSets []string
colors []string
format string
hashArray []int64
hexDigest string
iter int
hashCount int
sets []string
name string
materialPath string
AssembleOptions
}
type AssembleOptions struct {
RoboSet, Colors, BgSet string //optional
OutputPath string //optional default current dir
X int //optional default 300
Y int //optional default 300
}
//newResource new resource
func NewResource(text string, options *AssembleOptions) *resource {
if text == "" {
log.Fatalln("text is empty, you must set text")
}
r := &resource{}
r.hashCount = 11
h := sha512.New()
if _, err := h.Write([]byte(text)); err != nil {
log.Fatalln(err)
}
r.hexDigest = hex.EncodeToString(h.Sum(nil))
r.createHahes(r.hashCount)
_, filename, _, ok := runtime.Caller(0)
if !ok {
log.Fatalln("runtime.Caller(0) failed")
}
r.materialPath = filepath.Dir(filename) + "/" + "material"
r.sets = listDirs(r.materialPath + "/sets")
r.bgSets = listDirs(r.materialPath + "/backgrounds")
r.colors = listDirs(r.materialPath + "/sets/set1")
r.format = "png"
r.iter = 4
r.name = text
if options.X == 0 {
r.X = 300
}
if options.Y == 0 {
r.Y = 300
}
if options.BgSet == "bmp" {
log.Fatalln("bmp is not supported yet")
}
if options.OutputPath == "" {
r.OutputPath = "./"
}
r.OutputPath = filepath.Dir(options.OutputPath)
return r
}
//createHahes createHahes
func (r *resource) createHahes(count int) {
for i := 0; i < count; i++ {
blockSize := len(r.hexDigest) / count
currentStart := (1+i)*blockSize - blockSize
currentEnd := (1 + i) * blockSize
temp, err := strconv.ParseInt(r.hexDigest[currentStart:currentEnd], 16, 64)
if err != nil {
log.Fatalln(err)
}
r.hashArray = append(r.hashArray, temp)
}
}
//listDirs dir list
func listDirs(path string) []string {
rtn := []string{}
files, err := ioutil.ReadDir(path)
if err != nil {
log.Fatalln(err)
return rtn
}
for _, f := range files {
rtn = append(rtn, f.Name())
}
return rtn
}
//getListOfFiles dir file list
func (r *resource) getListOfFiles(path string) []string {
chosenFiles := []string{}
directories := []string{}
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() && strings.Contains(path, "#") {
directories = append(directories, path)
}
return nil
})
if err != nil {
log.Fatal(err)
}
sort.Strings(directories)
for _, v := range directories {
filesInDir := []string{}
err := filepath.Walk(v, func(v string, info os.FileInfo, err error) error {
if !info.IsDir() {
filesInDir = append(filesInDir, v)
}
return nil
})
if err != nil {
log.Fatal(err)
}
chosenFiles = append(chosenFiles, filesInDir[r.hashArray[r.iter]%int64(len(filesInDir))])
r.iter += 1
}
//chosenFiles E.g. [material\sets\set1\blue\003#01Body\000#blue_body-10.png material\sets\set1\blue\003#01Body\007#blue_body-06.png material\sets\set1\blue\004#02Face\000#blue_face-07.png material\sets\set1\blue\002#Accessory\002#blue_accessory-07.png material\sets\set1\blue\001#Eyes\009#blue_eyes-04.png material\sets\set1\blue\000#Mouth\009#blue_mouth-03.png]
return chosenFiles
}
//Assemble the original method build our robot return the robot image
func (r *resource) AssembleOrigin() (image.Image, error) {
if r.RoboSet == "any" {
r.RoboSet = r.sets[r.hashArray[1]%int64(len(r.sets))]
} else if status, _ := isContain(r.RoboSet, r.sets); !status {
r.RoboSet = r.sets[0]
}
if r.RoboSet == "set1" {
if exist, _ := isContain(r.Colors, r.colors); exist {
r.RoboSet = "set1/" + r.Colors
} else {
r.RoboSet = "set1/" + r.colors[r.hashArray[0]%int64(len(r.colors))]
}
}
if r.BgSet == "any" {
r.BgSet = r.bgSets[r.hashArray[2]%int64(len(r.bgSets))]
}
roboparts := r.getListOfFiles(r.materialPath + "/sets/" + r.RoboSet + "/")
roboparts = sortSets(roboparts)
var background string
if r.BgSet != "" {
bgList := []string{}
temp := listDirs(r.materialPath + "/backgrounds/" + r.BgSet)
for _, v := range temp {
if !strings.HasPrefix(v, ".") {
bgList = append(bgList, r.materialPath+"/backgrounds/"+r.BgSet+"/"+v)
}
}
background = bgList[r.hashArray[3]%int64(len(bgList))]
}
//roboparts[0]: material\sets\set1\white\003#01Body\006#white_body-05.png
imgFile, err := os.Open(roboparts[0])
if err != nil {
return nil, err
}
imgDec, _, err := image.Decode(imgFile)
if err != nil {
return nil, err
}
defer imgFile.Close()
resizeImg := resize.Resize(1024, 1024, imgDec, resize.Lanczos3)
newImg := image.NewRGBA(image.Rect(0, 0, 1024, 1024))
draw.Draw(newImg, newImg.Bounds(), resizeImg, resizeImg.Bounds().Min, draw.Over)
for _, v := range roboparts {
tempFile, err := os.Open(v)
if err != nil {
log.Fatalln(err)
}
tempImg, _, err := image.Decode(tempFile)
if err != nil {
log.Fatal(err)
}
tempFile.Close()
tempResizeImg := resize.Resize(1024, 1024, tempImg, resize.Lanczos3)
draw.Draw(newImg, newImg.Bounds(), newImg, newImg.Bounds().Min, draw.Over)
draw.Draw(newImg, newImg.Bounds(), tempResizeImg, newImg.Bounds().Min, draw.Over)
}
if r.BgSet != "" {
imgFile, err := os.Open(background)
if err != nil {
return nil, err
}
tempImg, _, err := image.Decode(imgFile)
if err != nil {
return nil, err
}
imgFile.Close()
tempResizeImg := resize.Resize(1024, 1024, tempImg, resize.Lanczos3)
draw.Draw(newImg, newImg.Bounds(), tempResizeImg, tempImg.Bounds().Min, draw.Over)
}
resizeImg = resize.Resize(uint(r.X), uint(r.Y), newImg, resize.Lanczos3)
return resizeImg, nil
}
//GenerateJPEG generate type jpeg image
func (r *resource) GenerateJPEG() (string, error) {
r.format = "jpeg"
i, err := r.AssembleOrigin()
if err != nil {
return "", err
}
output := fmt.Sprintf("%s/%s.%s", r.OutputPath, r.name, r.format)
out, err := os.Create(output)
if err != nil {
return "", err
}
defer out.Close()
if err := jpeg.Encode(out, i, nil); err != nil {
return "", err
}
return output, nil
}
//GenerateJPG generate type jpg image
func (r *resource) GenerateJPG() (string, error) {
r.format = "jpg"
i, err := r.AssembleOrigin()
if err != nil {
return "", err
}
output := fmt.Sprintf("%s/%s.%s", r.OutputPath, r.name, r.format)
out, err := os.Create(output)
if err != nil {
return "", err
}
defer out.Close()
if err := jpeg.Encode(out, i, nil); err != nil {
return "", err
}
return output, nil
}
//GeneratePNG generate type png image
//Recommended to use png format
func (r *resource) GeneratePNG() (string, error) {
r.format = "png"
i, err := r.AssembleOrigin()
if err != nil {
return "", err
}
output := fmt.Sprintf("%s/%s.%s", r.OutputPath, r.name, r.format)
out, err := os.Create(output)
if err != nil {
return "", err
}
defer out.Close()
if err := png.Encode(out, i); err != nil {
return "", err
}
return output, nil
}
func (r *resource) GenerateBase64() ([]byte, error) {
r.format = "png"
i, err := r.AssembleOrigin()
if err != nil {
return []byte{}, err
}
buff := bytes.NewBuffer(nil)
if err := png.Encode(buff, i); err != nil {
return []byte{}, err
}
dist := make([]byte, base64.StdEncoding.EncodedLen(buff.Len()))
base64.StdEncoding.Encode(dist, buff.Bytes())
return dist, nil
}
//isContain is slice contain obj
func isContain(obj string, slice []string) (bool, int) {
for k, v := range slice {
if obj == v {
return true, k
}
}
return false, -1
}
//isContain is slice contain like obj
func isContainLike(obj string, slice []string) (bool, int) {
for k, v := range slice {
if strings.Contains(v, obj) {
return true, k
}
}
return false, -1
}
//sortSets origin python: roboparts.sort(key=lambda x: x.split("#")[1])
func sortSets(sets []string) []string {
var temp, rtn []string
for _, v := range sets {
temp = append(temp, strings.Split(v, "#")[1])
}
sort.Strings(temp)
//E.g. [01Body 02Face Accessory Eyes Mouth]
for _, v := range temp {
if exist, key := isContainLike(v, sets); exist {
rtn = append(rtn, sets[key])
}
}
if len(rtn) == 0 {
log.Fatal("sortSets length 0")
}
//[003#01Body 004#02Face 002#Accessory 001#Eyes 000#Mouth]
return rtn
}