-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexiftool.go
125 lines (99 loc) · 2.13 KB
/
exiftool.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
package exiftool
import (
"bytes"
"io"
"os/exec"
"regexp"
"strconv"
"strings"
)
const (
gpsPrecisionFmt = "%.15f"
)
type Exif struct {
DateTimeOriginal string
GPS struct {
Latitude float64
Longitude float64
}
}
func Decode(r io.Reader) (*Exif, error) {
args := []string{"-c", gpsPrecisionFmt, "-"}
cmd := exec.Command("exiftool", args...)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
defer stdin.Close()
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
defer stdout.Close()
err = cmd.Start()
if err != nil {
return nil, err
}
go func(in io.WriteCloser, r io.Reader) {
defer in.Close()
io.Copy(in, r)
}(stdin, r)
done := make(chan bool)
out := new(bytes.Buffer)
go func(stdout io.ReadCloser) {
defer stdout.Close()
io.Copy(out, stdout)
done <- true
}(stdout)
<-done
err = cmd.Wait()
if err != nil {
return nil, err
}
return parseOutput(out.Bytes())
}
func DecodeFileAtPath(p string) (*Exif, error) {
args := []string{"-c", gpsPrecisionFmt, p}
out, err := exec.Command("exiftool", args...).Output()
if err != nil {
return nil, err
}
return parseOutput(out)
}
func parseOutput(out []byte) (*Exif, error) {
e := new(Exif)
for _, l := range strings.Split(string(out), "\n") {
parts := strings.SplitN(l, ": ", 2)
if len(parts) != 2 {
continue
}
field, value := parts[0], parts[1]
if ok, _ := regexp.MatchString("Date/Time Original", field); ok {
e.DateTimeOriginal = value
} else if ok, _ := regexp.MatchString("GPS Latitude +$", field); ok {
v, err := valueForCoordinateString(value)
if err == nil {
e.GPS.Latitude = v
}
} else if ok, _ := regexp.MatchString("GPS Longitude +$", field); ok {
v, err := valueForCoordinateString(value)
if err == nil {
e.GPS.Longitude = v
}
}
}
return e, nil
}
func valueForCoordinateString(coord string) (float64, error) {
parts := strings.Split(coord, " ")
numStr, dir := parts[0], parts[1]
num, err := strconv.ParseFloat(numStr, 64)
if err != nil {
return 0.0, err
}
sign := 1.0
if dir == "W" || dir == "S" {
sign = -1.0
}
return (num * sign), nil
}