1 /** \file test-extract.c
2 * \brief Extract EXIF data from a file and write it to another file.
3 *
4 * Copyright (C) 2019 Dan Fandrich <dan@coneharvesters.com>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301 USA.
20 *
21 */
22
23 #include "libexif/exif-data.h"
24
25 #include <string.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28
29
30 static const unsigned char header[4] = {'\xff', '\xd8', '\xff', '\xe1'};
31
main(const int argc,const char * argv[])32 int main(const int argc, const char *argv[])
33 {
34 int first = 1;
35 const char *fn = "input.jpg";
36 const char *outfn = "output.exif";
37 ExifData *d;
38 unsigned char *buf;
39 unsigned int len;
40 FILE *f;
41 unsigned char lenbuf[2];
42
43 if (argc > 1 && !strcmp(argv[1], "-o")) {
44 outfn = argv[2];
45 first += 2;
46 }
47 if (argc > first) {
48 fn = argv[first];
49 ++first;
50 }
51 if (argc > first) {
52 fprintf (stderr, "Too many arguments\n");
53 return 1;
54 }
55
56 d = exif_data_new_from_file(fn);
57 if (!d) {
58 fprintf (stderr, "Could not load data from '%s'!\n", fn);
59 return 1;
60 }
61
62 exif_data_save_data(d, &buf, &len);
63 exif_data_unref(d);
64
65 if (!buf) {
66 fprintf (stderr, "Could not extract EXIF data!\n");
67 return 2;
68 }
69
70 f = fopen(outfn, "wb");
71 if (!f) {
72 fprintf (stderr, "Could not open '%s' for writing!\n", outfn);
73 return 1;
74 }
75 /* Write EXIF with headers and length. */
76 if (fwrite(header, 1, sizeof(header), f) != sizeof(header)) {
77 fprintf (stderr, "Could not write to '%s'!\n", outfn);
78 return 3;
79 }
80 /*
81 * FIXME: The buffer from exif_data_save_data() seems to contain extra 0xffd8
82 * 0xffd9 JPEG markers at the end that I wasn't expecting, making the length
83 * seem too long. Should those markers really be included?
84 */
85 exif_set_short(lenbuf, EXIF_BYTE_ORDER_MOTOROLA, len);
86 if (fwrite(lenbuf, 1, 2, f) != 2) {
87 fprintf (stderr, "Could not write to '%s'!\n", outfn);
88 return 3;
89 }
90 if (fwrite(buf, 1, len, f) != len) {
91 fprintf (stderr, "Could not write to '%s'!\n", outfn);
92 return 3;
93 }
94 if (fclose(f) != 0) {
95 fprintf (stderr, "Could not close '%s'!\n", outfn);
96 return 3;
97 }
98 free(buf);
99 fprintf (stderr, "Wrote EXIF data to '%s'\n", outfn);
100
101 return 0;
102 }
103