-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
498 lines (436 loc) · 12.1 KB
/
main.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package main
import (
"flag"
"fmt"
"github.com/disintegration/imaging"
"github.com/rwcarlsen/goexif/exif"
"github.com/twpayne/go-kml"
"image/color"
"io/ioutil"
"log"
"os"
filepath2 "path/filepath"
"sort"
"strconv"
"strings"
)
// flags
var help bool
var imgDir string
var outDir string
var dataFilepath string
var sortByTime bool
var genPath bool
var includeNoLocation bool
var pathColorStr string
var kmz bool
var mode string
var base64images bool
var name string
var imageMaxSize int
// other global variables
var tempDir string
var dataFileItems dataArr
var isExternalPreferable = true
var isExternalIconPreferable = false
var iconMaxSize = 64
var availableModes = map[string]func (el *kml.CompoundElement, img *imagePlacemark){
"g-earth-web": addGxCarouselPlacemark,
"g-earth-web-panel": addGxPanelHtmlImage,
"g-earth-pro": addHtmlImagePlacemark,
"g-maps": addDescriptionImagePlacemark,
"g-earth-photo-overlay": addPhotoOverlayPlacemark,
}
func init() {
flag.BoolVar(&help, "h", false, "")
flag.BoolVar(&help, "help", false, "")
flag.StringVar(&imgDir, "i", "", "Input directory with images (required)")
flag.StringVar(&outDir, "o", "", "Output directory for generated KML file and other copied files. Must be empty or not exist! (required)")
flag.StringVar(&mode, "mode", "g-earth-web", fmt.Sprintf("Different apps use different types of image representation: %s", getModesKeys()))
flag.StringVar(&dataFilepath, "data", "", "JSON or YAML file with custom image information\n(it has higher priority than the EXIF info)")
flag.BoolVar(&sortByTime, "timesort", false, "Sort images by time (DateTimeOriginal eventually DateTime)")
flag.BoolVar(&genPath, "path", false, "Generate path (-timesort is recommended)")
flag.StringVar(&pathColorStr, "pathcolor", "00ff7fff", "Color of the path; format (hex): 'rrggbb' or 'rrggbbaa'")
flag.BoolVar(&includeNoLocation, "include-no-location", false, "Do not skip images with no location (they are placed on [0,0])")
flag.BoolVar(&kmz, "kmz", false, "Create KMZ file (zip the output directory)")
flag.BoolVar(&base64images, "base64", false, "Embed images in base64 in the KML file")
flag.StringVar(&name, "name", "", "Project name")
flag.IntVar(&imageMaxSize, "maxsize", 1600, "Resize internal images to fit into a MAXSIZE x MAXSIZE box")
}
func main() {
flag.Parse()
handleHelp()
checkCmd()
setup()
fmt.Println("Indexing images...")
images, err := indexImages(imgDir)
fatalIfErr(err)
tempDir, err = ioutil.TempDir("", "photo-map")
fatalIfErr(err)
defer func(){
err := os.RemoveAll(tempDir)
printIfErr(err)
}()
fmt.Println("Preparing images...")
createThumbnailsAndResized(images)
fmt.Println("Generating KML document...")
k, doc := getKmlDoc(name)
if sortByTime {
orderImagesByTime(images)
}
if genPath {
generatePath(images, doc)
}
n := 1
for i, img := range images {
if base64images {
err := setBase64Image(img)
printIfErr(err)
err = setBase64Icon(img)
printIfErr(err)
} else {
collectFiles(img)
}
warnIfNoLocation(img)
if img.hasLocation || includeNoLocation {
img.description = img.dateTime.String()
img.name = strconv.Itoa(n)
n++
availableModes[mode](doc, img)
}
images[i] = nil
}
of, err := createFile(joinPaths(outDir, "doc.kml"))
fatalIfErr(err)
fatalIfErr(k.WriteIndent(of, "", " "))
if kmz {
fmt.Println("Creating KMZ file...")
zipFolderContents(outDir, joinPaths(outDir, "doc.kmz"))
}
fmt.Println("Done!")
}
/*
Checks the flags and arguments. If something is not right, fatal error is produced.
-i and -o flags are required, any additional arguments are forbidden.
*/
func checkCmd() {
if imgDir == "" {
log.Println("The input directory is required: -i path/to/dir")
defer os.Exit(1)
}
if outDir == "" {
log.Println("The output directory is required: -o path/to/dir")
defer os.Exit(1)
}
if _, ok := availableModes[mode]; !ok {
log.Println("Unknown mode: " + mode)
defer os.Exit(1)
}
if flag.NArg() > 0 {
log.Println("Unexpected arguments: " + strings.Join(flag.Args(), " "))
defer os.Exit(1)
}
}
/*
Handles help flag -h. If the help is requested, prints program description and usage, and exits.
*/
func handleHelp() {
if help {
fmt.Println("photo-map")
fmt.Println("An image gallery placed on a map!")
fmt.Println("\nSee https://github.com/sykoram/photo-map for documentation and more information.")
fmt.Println("\nUsage:")
flag.PrintDefaults()
os.Exit(0)
}
}
/*
Setup:
Normalizes paths, sets outFilesDir;
Loads JSON or YAML file with custom image data if possible.
*/
func setup() {
imgDir = normalizePath(imgDir)
outDir = normalizePath(outDir)
if dataFilepath != "" {
dataFilepath = normalizePath(dataFilepath)
var data dataObj
var err error
switch strings.ToLower(filepath2.Ext(dataFilepath)) {
case ".json":
data, err = loadJson(dataFilepath)
fatalIfErr(err)
case ".yaml":
data, err = loadYaml(dataFilepath)
fatalIfErr(err)
}
if data["items"] == nil {
log.Fatalln("Cannot find key 'items' in the data file.")
} else {
dataFileItems = data["items"].(dataArr)
}
}
var err error
pathLineColor, err = parseHexColor(pathColorStr)
if err != nil {
log.Fatalln("color-parsing error:", err)
}
}
/*
Converts a hex-string representation of a color to color.RGBA.
*/
func parseHexColor(s string) (color.RGBA, error) {
strings.ReplaceAll(s, "#", "")
if len(s) == 6 {
s += "ff"
}
c := color.RGBA{}
_, err := fmt.Sscanf(s, "%2x%2x%2x%2x", &c.R, &c.G, &c.B, &c.A)
return c, err
}
/*
Returns imagePlacemarks created using both internal and external images.
Internal images are collected from the rootDir.
Purely external images are loaded from the JSON or YAML data file.
The returned structs have kmlPaths already set.
*/
func indexImages(rootDir string) (images []*imagePlacemark, err error) {
images, err = getInternalImages(rootDir)
if err != nil {
return
}
externalImages, err := getExternalImages()
if err != nil {
return
}
images = append(images, externalImages...)
for i := range images {
images[i].setKmlPaths(isExternalPreferable, isExternalIconPreferable)
}
return
}
/*
Searches the given dir, collects images returns them as image structs. .thumbnail dirs are ignored.
*/
func getInternalImages(rootDir string) (images []*imagePlacemark, err error) {
rootDir = normalizePath(rootDir)
images = make([]*imagePlacemark, 0)
err = filepath2.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
path = normalizePath(path)
path = strings.TrimPrefix(path, rootDir+"/")
printIfErr(err)
if err != nil {
return nil
}
// skip .thumbnails
if strings.Contains(path, ".thumbnails") {
return filepath2.SkipDir
}
if info.Mode().IsRegular() && isImage(info) {
images = append(images, prepareInternalImage(rootDir, path))
}
return nil
})
return
}
/*
Prepares an internal image struct: loads EXIF and JSON and sets properties
*/
func prepareInternalImage(rootDir, rootRelPath string) *imagePlacemark {
img := imagePlacemark{
path: rootRelPath,
rootDir: rootDir,
iconPath: joinPaths(".thumbnails", rootRelPath), // the icon does not exit yet
}
err := img.loadOrigExif(joinPaths(img.rootDir, img.path))
if err != nil && exif.IsCriticalError(err) {
log.Println("EXIF of", img.path, "has a critical error:", err)
} else {
img.applyDataFromExif()
}
// overwrite data from exif with data from json
if dataFileItems != nil {
for _, obj := range dataFileItems {
if f, ok := obj.(dataObj)["file"]; ok {
fs := normalizePath(f.(string))
if fs == img.path {
img.setCustomData(obj.(dataObj))
img.applyCustomData()
}
}
}
}
return &img
}
/*
Returns imagePlacemarks with purely external images loaded from the JSON/YAML file.
*/
func getExternalImages() (images []*imagePlacemark, err error) {
images = make([]*imagePlacemark, 0)
if dataFileItems == nil {
return
}
for _, obj := range dataFileItems {
_, isExt := obj.(dataObj)["external"]
if _, isInt := obj.(dataObj)["file"]; isExt && !isInt { // only pure external images without local files
img := imagePlacemark{}
img.setCustomData(obj.(dataObj))
img.applyCustomData() // sets also externalPath
images = append(images, &img)
}
}
return
}
/*
Creates thumbnail and resized version in the tempDir. Sets image rootDir to the tempDir.
*/
func createThumbnailsAndResized(images []*imagePlacemark) {
for i, imgPm := range images {
if !imgPm.isInternal && !imgPm.isIconInternal {
continue
}
img, err := imaging.Open(joinPaths(imgPm.rootDir, imgPm.path), imaging.AutoOrientation(true))
if err != nil {
printIfErr(err)
continue
}
images[i].rootDir = tempDir
if imgPm.isInternal {
resized := imaging.Fit(img, imageMaxSize, imageMaxSize, imaging.Lanczos)
err = createDir(filepath2.Dir(joinPaths(tempDir, imgPm.path)))
printIfErr(err)
err = imaging.Save(resized, joinPaths(tempDir, imgPm.path), imaging.JPEGQuality(75))
printIfErr(err)
}
if imgPm.isIconInternal {
thumbnail := imaging.Fit(img, iconMaxSize, iconMaxSize, imaging.Lanczos)
err = createDir(filepath2.Dir(joinPaths(tempDir, imgPm.iconPath)))
printIfErr(err)
images[i].iconPath += ".png"
err = imaging.Save(thumbnail, joinPaths(tempDir, imgPm.iconPath), imaging.JPEGQuality(75))
printIfErr(err)
}
}
}
/*
Copies resized image file or thumbnail from the tempDir to the output directory if necessary.
*/
func collectFiles(img *imagePlacemark) {
if img.isInternal {
printIfErr(copyFile(joinPaths(tempDir, img.path), joinPaths(outDir, img.pathInKml)))
}
if img.isIconInternal {
printIfErr(copyFile(joinPaths(tempDir, img.iconPath), joinPaths(outDir, img.iconPathInKml)))
}
}
/*
Orders images by their timestamp. Warns if an image has no dateTime.
*/
func orderImagesByTime(images []*imagePlacemark) {
for _, img := range images {
if !img.hasDateTime {
path := ""
if img.isInternal {
path = img.path
} else {
path = img.externalPath
}
log.Printf("%s has no dateTime", path)
}
}
sort.Slice(images, func(i int, j int) bool {
return images[i].dateTime.Before(images[j].dateTime)
})
}
/*
Generates a path (line) that connects the images.
Images with no location are skipped.
*/
func generatePath(images []*imagePlacemark, doc *kml.CompoundElement) {
coords := make([]kml.Coordinate, 0)
for _, img := range images {
if img.hasLocation {
ic := kml.Coordinate{Lon: img.longitude, Lat: img.latitude}
if len(coords) == 0 || coords[len(coords)-1] != ic { // ignore coordinates if same as previous
coords = append(coords, ic)
}
}
}
createLine(doc, coords)
}
/*
Sets pathInKml to base64 data of the image file if the image is internal.
*/
func setBase64Image(img *imagePlacemark) error {
if img.isInternal {
mimeType, err := getImageMimeType(strings.Replace(filepath2.Ext(img.pathInKml), ".", "", 1))
if err != nil {
return err
}
b64Data, err := getBase64Data(joinPaths(img.rootDir, img.path))
if err != nil {
return err
}
img.pathInKml = "data:" + mimeType + ";base64,"
img.pathInKml += string(b64Data)
}
return nil
}
/*
Sets pathInKml to base64 data of the thumbnail file if the icon is internal.
*/
func setBase64Icon(img *imagePlacemark) error {
if img.isIconInternal {
mimeType, err := getImageMimeType(strings.Replace(filepath2.Ext(img.iconPathInKml), ".", "", 1))
if err != nil {
return err
}
b64Data, err := getBase64Data(joinPaths(img.rootDir, img.iconPath))
if err != nil {
return err
}
img.iconPathInKml = "data:" + mimeType + ";base64,"
img.iconPathInKml += string(b64Data)
}
return nil
}
/*
Warns if the image has no location.
*/
func warnIfNoLocation(img *imagePlacemark) {
if !img.hasLocation {
path := ""
if img.isInternal {
path = img.path
} else {
path = img.externalPath
}
log.Println(path, "has no location")
}
}
/*
Returns string keys of the modes
*/
func getModesKeys() []string {
var sm []string
for key := range availableModes {
sm = append(sm, key)
}
return sm
}
/*
If there is an error, produces fatal error (prints the error, exits with a code 1).
*/
func fatalIfErr(err error) {
if err != nil {
log.Fatalln(err)
}
}
/*
If there is an error, prints it.
*/
func printIfErr(err error) {
if err != nil {
log.Println(err)
}
}