-
Notifications
You must be signed in to change notification settings - Fork 8
/
exiv.go
146 lines (110 loc) · 2.31 KB
/
exiv.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
package goexiv
// #cgo pkg-config: exiv2
// #include "helper.h"
// #include <stdlib.h>
import "C"
import (
"runtime"
"unsafe"
)
type Error struct {
code int
what string
}
type Image struct {
img *C.Exiv2Image
}
type ExifData struct {
img *Image // We point to img to keep it alive
data *C.Exiv2ExifData
}
type ExifDatum struct {
data *ExifData
datum *C.Exiv2ExifDatum
}
func (e *Error) Error() string {
return e.what
}
func (e *Error) Code() int {
return e.code
}
func makeError(cerr *C.Exiv2Error) *Error {
return &Error{
int(C.exiv2_error_code(cerr)),
C.GoString(C.exiv2_error_what(cerr)),
}
}
func makeImage(cimg *C.Exiv2Image) *Image {
img := &Image{
cimg,
}
runtime.SetFinalizer(img, func(x *Image) {
C.exiv2_image_free(x.img)
})
return img
}
func makeExifData(img *Image, cdata *C.Exiv2ExifData) *ExifData {
data := &ExifData{
img,
cdata,
}
runtime.SetFinalizer(data, func(x *ExifData) {
C.exiv2_exif_data_free(x.data)
})
return data
}
func makeExifDatum(data *ExifData, cdatum *C.Exiv2ExifDatum) *ExifDatum {
if cdatum == nil {
return nil
}
datum := &ExifDatum{
data,
cdatum,
}
runtime.SetFinalizer(datum, func(x *ExifDatum) {
C.exiv2_exif_datum_free(x.datum)
})
return datum
}
func Open(path string) (*Image, error) {
cpath := C.CString(path)
defer C.free(unsafe.Pointer(cpath))
var cerr *C.Exiv2Error
cimg := C.exiv2_image_factory_open(cpath, &cerr)
if cerr != nil {
err := makeError(cerr)
C.exiv2_error_free(cerr)
return nil, err
}
return makeImage(cimg), nil
}
func (i *Image) ReadMetadata() error {
var cerr *C.Exiv2Error
C.exiv2_image_read_metadata(i.img, &cerr)
if cerr != nil {
err := makeError(cerr)
C.exiv2_error_free(cerr)
return err
}
return nil
}
func (i *Image) GetExifData() *ExifData {
return makeExifData(i, C.exiv2_image_get_exif_data(i.img))
}
func (d *ExifData) FindKey(key string) (*ExifDatum, error) {
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
var cerr *C.Exiv2Error
cdatum := C.exiv2_exif_data_find_key(d.data, ckey, &cerr)
if cerr != nil {
err := makeError(cerr)
C.exiv2_error_free(cerr)
return nil, err
}
return makeExifDatum(d, cdatum), nil
}
func (d *ExifDatum) String() string {
cstr := C.exiv2_exif_datum_to_string(d.datum)
defer C.free(unsafe.Pointer(cstr))
return C.GoString(cstr)
}