Debian Codegraph @

src/com/drew/metadata/TagDescriptor.java

raw symbols SCIP
1 /*
2 * Copyright 2002-2019 Drew Noakes and contributors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * More information about this project is available at:
17 *
18 * https://drewnoakes.com/code/exif/
19 * https://github.com/drewnoakes/metadata-extractor
20 */
21 package com.drew.metadata;
22
23 import com.drew.lang.Rational;
24 import com.drew.lang.StringUtil;
25 import com.drew.lang.annotations.NotNull;
26 import com.drew.lang.annotations.Nullable;
27
28 import java.io.UnsupportedEncodingException;
29 import java.lang.reflect.Array;
30 import java.math.RoundingMode;
31 import java.nio.charset.Charset;
32 import java.text.DecimalFormat;
33 import java.text.SimpleDateFormat;
34 import java.util.ArrayList;
35 import java.util.Date;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39
40 /**
41 * Base class for all tag descriptor classes. Implementations are responsible for
42 * providing the human-readable string representation of tag values stored in a directory.
43 * The directory is provided to the tag descriptor via its constructor.
44 *
45 * @author Drew Noakes https://drewnoakes.com
46 */
47 public class TagDescriptor<T extends Directory>
48 {
49 @NotNull
50 protected final T _directory;
51
52 public TagDescriptor(@NotNull T directory)
53 {
54 _directory = directory;
55 }
56
57 /**
58 * Returns a descriptive value of the specified tag for this image.
59 * Where possible, known values will be substituted here in place of the raw
60 * tokens actually kept in the metadata segment. If no substitution is
61 * available, the value provided by <code>getString(tagType)</code> will be returned.
62 *
63 * @param tagType the tag to find a description for
64 * @return a description of the image's value for the specified tag, or
65 * <code>null</code> if the tag hasn't been defined.
66 */
67 @Nullable
68 public String getDescription(int tagType)
69 {
70 Object object = _directory.getObject(tagType);
71
72 if (object == null)
73 return null;
74
75 // special presentation for long arrays
76 if (object.getClass().isArray()) {
77 final int length = Array.getLength(object);
78 if (length > 16) {
79 return String.format("[%d values]", length);
80 }
81 }
82
83 if (object instanceof Date) {
84 // Produce a date string having a format that includes the offset in form "+00:00"
85 return new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy")
86 .format((Date) object)
87 .replaceAll("([0-9]{2} [^ ]+)$", ":$1");
88 }
89
90 // no special handling required, so use default conversion to a string
91 return _directory.getString(tagType);
92 }
93
94 /**
95 * Takes a series of 4 bytes from the specified offset, and converts these to a
96 * well-known version number, where possible.
97 * <p>
98 * Two different formats are processed:
99 * <ul>
100 * <li>[30 32 31 30] -&gt; 2.10</li>
101 * <li>[0 1 0 0] -&gt; 1.00</li>
102 * </ul>
103 *
104 * @param components the four version values
105 * @param majorDigits the number of components to be
106 * @return the version as a string of form "2.10" or null if the argument cannot be converted
107 */
108 @Nullable
109 public static String convertBytesToVersionString(@Nullable int[] components, final int majorDigits)
110 {
111 if (components == null)
112 return null;
113 StringBuilder version = new StringBuilder();
114 for (int i = 0; i < 4 && i < components.length; i++) {
115 if (i == majorDigits)
116 version.append('.');
117 char c = (char)components[i];
118 if (c < '0')
119 c += '0';
120 if (i == 0 && c == '0')
121 continue;
122 version.append(c);
123 }
124 return version.toString();
125 }
126
127 @Nullable
128 protected String getVersionBytesDescription(final int tagType, int majorDigits)
129 {
130 int[] values = _directory.getIntArray(tagType);
131 return values == null ? null : convertBytesToVersionString(values, majorDigits);
132 }
133
134 @Nullable
135 protected String getIndexedDescription(final int tagType, @NotNull String... descriptions)
136 {
137 return getIndexedDescription(tagType, 0, descriptions);
138 }
139
140 @Nullable
141 protected String getIndexedDescription(final int tagType, final int baseIndex, @NotNull String... descriptions)
142 {
143 final Long index = _directory.getLongObject(tagType);
144 if (index == null)
145 return null;
146 final long arrayIndex = index - baseIndex;
147 if (arrayIndex >= 0 && arrayIndex < (long)descriptions.length) {
148 String description = descriptions[(int)arrayIndex];
149 if (description != null)
150 return description;
151 }
152 return "Unknown (" + index + ")";
153 }
154
155 @Nullable
156 protected String getByteLengthDescription(final int tagType)
157 {
158 byte[] bytes = _directory.getByteArray(tagType);
159 if (bytes == null)
160 return null;
161 return String.format("(%d byte%s)", bytes.length, bytes.length == 1 ? "" : "s");
162 }
163
164 @Nullable
165 protected String getSimpleRational(final int tagType)
166 {
167 Rational value = _directory.getRational(tagType);
168 if (value == null)
169 return null;
170 return value.toSimpleString(true);
171 }
172
173 @Nullable
174 protected String getDecimalRational(final int tagType, final int decimalPlaces)
175 {
176 Rational value = _directory.getRational(tagType);
177 if (value == null)
178 return null;
179 return String.format("%." + decimalPlaces + "f", value.doubleValue());
180 }
181
182 @Nullable
183 protected String getFormattedInt(final int tagType, @NotNull final String format)
184 {
185 Integer value = _directory.getInteger(tagType);
186 if (value == null)
187 return null;
188 return String.format(format, value);
189 }
190
191 @Nullable
192 protected String getFormattedFloat(final int tagType, @NotNull final String format)
193 {
194 Float value = _directory.getFloatObject(tagType);
195 if (value == null)
196 return null;
197 return String.format(format, value);
198 }
199
200 @Nullable
201 protected String getFormattedString(final int tagType, @NotNull final String format)
202 {
203 String value = _directory.getString(tagType);
204 if (value == null)
205 return null;
206 return String.format(format, value);
207 }
208
209 @Nullable
210 protected String getEpochTimeDescription(final int tagType)
211 {
212 // TODO have observed a byte[8] here which is likely some kind of date (ticks as long?)
213 Long value = _directory.getLongObject(tagType);
214 if (value == null)
215 return null;
216 return new Date(value).toString();
217 }
218
219 /**
220 * LSB first. Labels may be null, a String, or a String[2] with (low label,high label) values.
221 */
222 @Nullable
223 protected String getBitFlagDescription(final int tagType, @NotNull final Object... labels)
224 {
225 Integer value = _directory.getInteger(tagType);
226
227 if (value == null)
228 return null;
229
230 List<String> parts = new ArrayList<String>();
231
232 int bitIndex = 0;
233 while (labels.length > bitIndex) {
234 Object labelObj = labels[bitIndex];
235 if (labelObj != null) {
236 boolean isBitSet = (value & 1) == 1;
237 if (labelObj instanceof String[]) {
238 String[] labelPair = (String[])labelObj;
239 assert(labelPair.length == 2);
240 parts.add(labelPair[isBitSet ? 1 : 0]);
241 } else if (isBitSet && labelObj instanceof String) {
242 parts.add((String)labelObj);
243 }
244 }
245 value >>= 1;
246 bitIndex++;
247 }
248
249 return StringUtil.join(parts, ", ");
250 }
251
252 @Nullable
253 protected String get7BitStringFromBytes(final int tagType)
254 {
255 final byte[] bytes = _directory.getByteArray(tagType);
256
257 if (bytes == null)
258 return null;
259
260 int length = bytes.length;
261 for (int index = 0; index < bytes.length; index++) {
262 int i = bytes[index] & 0xFF;
263 if (i == 0 || i > 0x7F) {
264 length = index;
265 break;
266 }
267 }
268
269 return new String(bytes, 0, length);
270 }
271
272 @Nullable
273 protected String getStringFromBytes(int tag, Charset cs)
274 {
275 byte[] values = _directory.getByteArray(tag);
276
277 if (values == null)
278 return null;
279
280 try {
281 return new String(values, cs.name()).trim();
282 } catch (UnsupportedEncodingException e) {
283 return null;
284 }
285 }
286
287 @Nullable
288 protected String getRationalOrDoubleString(int tagType)
289 {
290 Rational rational = _directory.getRational(tagType);
291 if (rational != null)
292 return rational.toSimpleString(true);
293
294 Double d = _directory.getDoubleObject(tagType);
295 if (d != null) {
296 DecimalFormat format = new DecimalFormat("0.###");
297 return format.format(d);
298 }
299
300 return null;
301 }
302
303 @NotNull
304 protected static String getFStopDescription(double fStop)
305 {
306 DecimalFormat format = new DecimalFormat("0.0");
307 format.setRoundingMode(RoundingMode.HALF_UP);
308 return "f/" + format.format(fStop);
309 }
310
311 @NotNull
312 protected static String getFocalLengthDescription(double mm)
313 {
314 DecimalFormat format = new DecimalFormat("0.#");
315 format.setRoundingMode(RoundingMode.HALF_UP);
316 return format.format(mm) + " mm";
317 }
318
319 @Nullable
320 protected String getLensSpecificationDescription(int tag)
321 {
322 Rational[] values = _directory.getRationalArray(tag);
323
324 if (values == null || values.length != 4 || (values[0].isZero() && values[2].isZero()))
325 return null;
326
327 StringBuilder sb = new StringBuilder();
328
329 if (values[0].equals(values[1]))
330 sb.append(values[0].toSimpleString(true)).append("mm");
331 else
332 sb.append(values[0].toSimpleString(true)).append('-').append(values[1].toSimpleString(true)).append("mm");
333
334 if (!values[2].isZero()) {
335 sb.append(' ');
336
337 DecimalFormat format = new DecimalFormat("0.0");
338 format.setRoundingMode(RoundingMode.HALF_UP);
339
340 if (values[2].equals(values[3]))
341 sb.append(getFStopDescription(values[2].doubleValue()));
342 else
343 sb.append("f/").append(format.format(values[2].doubleValue())).append('-').append(format.format(values[3].doubleValue()));
344 }
345
346 return sb.toString();
347 }
348
349 @Nullable
350 protected String getOrientationDescription(int tag)
351 {
352 return getIndexedDescription(tag, 1,
353 "Top, left side (Horizontal / normal)",
354 "Top, right side (Mirror horizontal)",
355 "Bottom, right side (Rotate 180)",
356 "Bottom, left side (Mirror vertical)",
357 "Left side, top (Mirror horizontal and rotate 270 CW)",
358 "Right side, top (Rotate 90 CW)",
359 "Right side, bottom (Mirror horizontal and rotate 90 CW)",
360 "Left side, bottom (Rotate 270 CW)");
361 }
362
363 @Nullable
364 protected String getShutterSpeedDescription(int tag)
365 {
366 // Thanks to Mark Edwards for spotting and patching a bug in the calculation of this
367 // description (spotted bug using a Canon EOS 300D).
368 // Thanks also to Gli Blr for spotting this bug.
369 Float apexValue = _directory.getFloatObject(tag);
370 if (apexValue == null)
371 return null;
372 if (apexValue <= 1) {
373 float apexPower = (float)(1 / (Math.exp(apexValue * Math.log(2))));
374 long apexPower10 = Math.round((double)apexPower * 10.0);
375 float fApexPower = (float)apexPower10 / 10.0f;
376 DecimalFormat format = new DecimalFormat("0.##");
377 format.setRoundingMode(RoundingMode.HALF_UP);
378 return format.format(fApexPower) + " sec";
379 } else {
380 int apexPower = (int)((Math.exp(apexValue * Math.log(2))));
381 return "1/" + apexPower + " sec";
382 }
383 }
384
385 // EXIF UserComment, GPSProcessingMethod and GPSAreaInformation
386 @Nullable
387 protected String getEncodedTextDescription(int tagType)
388 {
389 byte[] commentBytes = _directory.getByteArray(tagType);
390 if (commentBytes == null)
391 return null;
392 if (commentBytes.length == 0)
393 return "";
394
395 final Map<String, String> encodingMap = new HashMap<String, String>();
396 encodingMap.put("ASCII", System.getProperty("file.encoding")); // Someone suggested "ISO-8859-1".
397 encodingMap.put("UNICODE", "UTF-16LE");
398 encodingMap.put("JIS", "Shift-JIS"); // We assume this charset for now. Another suggestion is "JIS".
399
400 try {
401 if (commentBytes.length >= 10) {
402 String firstTenBytesString = new String(commentBytes, 0, 10);
403
404 // try each encoding name
405 for (Map.Entry<String, String> pair : encodingMap.entrySet()) {
406 String encodingName = pair.getKey();
407 String charset = pair.getValue();
408 if (firstTenBytesString.startsWith(encodingName)) {
409 // skip any null or blank characters commonly present after the encoding name, up to a limit of 10 from the start
410 for (int j = encodingName.length(); j < 10; j++) {
411 byte b = commentBytes[j];
412 if (b != '\0' && b != ' ')
413 return new String(commentBytes, j, commentBytes.length - j, charset).trim();
414 }
415 return new String(commentBytes, 10, commentBytes.length - 10, charset).trim();
416 }
417 }
418 }
419 // special handling fell through, return a plain string representation
420 return new String(commentBytes, System.getProperty("file.encoding")).trim();
421 } catch (UnsupportedEncodingException ex) {
422 return null;
423 }
424 }
425 }