Debian Codegraph @

src/com/drew/imaging/ImageMetadataReader.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.imaging;
22
23 import com.drew.imaging.avi.AviMetadataReader;
24 import com.drew.imaging.bmp.BmpMetadataReader;
25 import com.drew.imaging.eps.EpsMetadataReader;
26 import com.drew.imaging.gif.GifMetadataReader;
27 import com.drew.imaging.heif.HeifMetadataReader;
28 import com.drew.imaging.ico.IcoMetadataReader;
29 import com.drew.imaging.jpeg.JpegMetadataReader;
30 import com.drew.imaging.mp3.Mp3MetadataReader;
31 import com.drew.imaging.mp4.Mp4MetadataReader;
32 import com.drew.imaging.quicktime.QuickTimeMetadataReader;
33 import com.drew.imaging.pcx.PcxMetadataReader;
34 import com.drew.imaging.png.PngMetadataReader;
35 import com.drew.imaging.psd.PsdMetadataReader;
36 import com.drew.imaging.raf.RafMetadataReader;
37 import com.drew.imaging.tiff.TiffMetadataReader;
38 import com.drew.imaging.wav.WavMetadataReader;
39 import com.drew.imaging.webp.WebpMetadataReader;
40 import com.drew.lang.RandomAccessStreamReader;
41 import com.drew.lang.StringUtil;
42 import com.drew.lang.annotations.NotNull;
43 import com.drew.metadata.Directory;
44 import com.drew.metadata.Metadata;
45 import com.drew.metadata.Tag;
46 import com.drew.metadata.exif.ExifIFD0Directory;
47 import com.drew.metadata.file.FileSystemMetadataReader;
48 import com.drew.metadata.file.FileTypeDirectory;
49 import com.drew.metadata.xmp.XmpDirectory;
50
51 import java.io.*;
52 import java.util.ArrayList;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.Map;
56
57 /**
58 * Reads metadata from any supported file format.
59 * <p>
60 * This class a lightweight wrapper around other, specific metadata processors.
61 * During extraction, the file type is determined from the first few bytes of the file.
62 * Parsing is then delegated to one of:
63 *
64 * <ul>
65 * <li>{@link AviMetadataReader} for AVI files</li>
66 * <li>{@link BmpMetadataReader} for BMP files</li>
67 * <li>{@link FileSystemMetadataReader} for metadata from the file system when a {@link File} is provided</li>
68 * <li>{@link GifMetadataReader} for GIF files</li>
69 * <li>{@link IcoMetadataReader} for ICO files</li>
70 * <li>{@link JpegMetadataReader} for JPEG files</li>
71 * <li>{@link Mp4MetadataReader} for MPEG-4 files</li>
72 * <li>{@link PcxMetadataReader} for PCX files</li>
73 * <li>{@link PngMetadataReader} for PNG files</li>
74 * <li>{@link PsdMetadataReader} for Photoshop files</li>
75 * <li>{@link QuickTimeMetadataReader} for QuickTime files</li>
76 * <li>{@link RafMetadataReader} for RAF files</li>
77 * <li>{@link TiffMetadataReader} for TIFF and (most) RAW files</li>
78 * <li>{@link WavMetadataReader} for WAV files</li>
79 * <li>{@link WebpMetadataReader} for WebP files</li>
80 * </ul>
81 *
82 * If you know the file type you're working with, you may use one of the above processors directly.
83 * For most scenarios it is simpler, more convenient and more robust to use this class.
84 * <p>
85 * {@link FileTypeDetector} is used to determine the provided image's file type, and therefore
86 * the appropriate metadata reader to use.
87 *
88 * @author Drew Noakes https://drewnoakes.com
89 */
90 public class ImageMetadataReader
91 {
92 /**
93 * Reads metadata from an {@link InputStream}.
94 *
95 * @param inputStream a stream from which the file data may be read. The stream must be positioned at the
96 * beginning of the file's data.
97 * @return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
98 * @throws ImageProcessingException if the file type is unknown, or for general processing errors.
99 */
100 @NotNull
101 public static Metadata readMetadata(@NotNull final InputStream inputStream) throws ImageProcessingException, IOException
102 {
103 return readMetadata(inputStream, -1);
104 }
105
106 /**
107 * Reads metadata from an {@link InputStream} of known length.
108 *
109 * @param inputStream a stream from which the file data may be read. The stream must be positioned at the
110 * beginning of the file's data.
111 * @param streamLength the length of the stream, if known, otherwise -1.
112 * @return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
113 * @throws ImageProcessingException if the file type is unknown, or for general processing errors.
114 */
115 @NotNull
116 public static Metadata readMetadata(@NotNull final InputStream inputStream, final long streamLength) throws ImageProcessingException, IOException
117 {
118 BufferedInputStream bufferedInputStream = inputStream instanceof BufferedInputStream
119 ? (BufferedInputStream)inputStream
120 : new BufferedInputStream(inputStream);
121
122 FileType fileType = FileTypeDetector.detectFileType(bufferedInputStream);
123
124 Metadata metadata = readMetadata(bufferedInputStream, streamLength, fileType);
125
126 metadata.addDirectory(new FileTypeDirectory(fileType));
127
128 return metadata;
129 }
130
131 /**
132 * Reads metadata from an {@link InputStream} of known length and file type.
133 *
134 * @param inputStream a stream from which the file data may be read. The stream must be positioned at the
135 * beginning of the file's data.
136 * @param streamLength the length of the stream, if known, otherwise -1.
137 * @param fileType the file type of the data stream.
138 * @return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
139 * @throws ImageProcessingException if the file type is unknown, or for general processing errors.
140 */
141 @NotNull
142 public static Metadata readMetadata(@NotNull final InputStream inputStream, final long streamLength, final FileType fileType) throws IOException, ImageProcessingException
143 {
144 switch (fileType) {
145 case Jpeg:
146 return JpegMetadataReader.readMetadata(inputStream);
147 case Tiff:
148 case Arw:
149 case Cr2:
150 case Nef:
151 case Orf:
152 case Rw2:
153 return TiffMetadataReader.readMetadata(new RandomAccessStreamReader(inputStream, RandomAccessStreamReader.DEFAULT_CHUNK_LENGTH, streamLength));
154 case Psd:
155 return PsdMetadataReader.readMetadata(inputStream);
156 case Png:
157 return PngMetadataReader.readMetadata(inputStream);
158 case Bmp:
159 return BmpMetadataReader.readMetadata(inputStream);
160 case Gif:
161 return GifMetadataReader.readMetadata(inputStream);
162 case Ico:
163 return IcoMetadataReader.readMetadata(inputStream);
164 case Pcx:
165 return PcxMetadataReader.readMetadata(inputStream);
166 case WebP:
167 return WebpMetadataReader.readMetadata(inputStream);
168 case Raf:
169 return RafMetadataReader.readMetadata(inputStream);
170 case Avi:
171 return AviMetadataReader.readMetadata(inputStream);
172 case Wav:
173 return WavMetadataReader.readMetadata(inputStream);
174 case QuickTime:
175 return QuickTimeMetadataReader.readMetadata(inputStream);
176 case Mp4:
177 return Mp4MetadataReader.readMetadata(inputStream);
178 case Mp3:
179 return Mp3MetadataReader.readMetadata(inputStream);
180 case Eps:
181 return EpsMetadataReader.readMetadata(inputStream);
182 case Heif:
183 return HeifMetadataReader.readMetadata(inputStream);
184 case Unknown:
185 throw new ImageProcessingException("File format could not be determined");
186 default:
187 return new Metadata();
188 }
189 }
190
191 /**
192 * Reads {@link Metadata} from a {@link File} object.
193 *
194 * @param file a file from which the image data may be read.
195 * @return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
196 * @throws ImageProcessingException for general processing errors.
197 */
198 @NotNull
199 public static Metadata readMetadata(@NotNull final File file) throws ImageProcessingException, IOException
200 {
201 InputStream inputStream = new FileInputStream(file);
202 Metadata metadata;
203 try {
204 metadata = readMetadata(inputStream, file.length());
205 } finally {
206 inputStream.close();
207 }
208 new FileSystemMetadataReader().read(file, metadata);
209 return metadata;
210 }
211
212 private ImageMetadataReader() throws Exception
213 {
214 throw new Exception("Not intended for instantiation");
215 }
216
217 /**
218 * An application entry point. Takes the name of one or more files as arguments and prints the contents of all
219 * metadata directories to <code>System.out</code>.
220 * <p>
221 * If <code>-thumb</code> is passed, then any thumbnail data will be written to a file with name of the
222 * input file having <code>.thumb.jpg</code> appended.
223 * <p>
224 * If <code>-markdown</code> is passed, then output will be in markdown format.
225 * <p>
226 * If <code>-hex</code> is passed, then the ID of each tag will be displayed in hexadecimal.
227 *
228 * @param args the command line arguments
229 */
230 public static void main(@NotNull String[] args)
231 {
232 Collection<String> argList = new ArrayList<String>(Arrays.asList(args));
233 boolean markdownFormat = argList.remove("-markdown");
234 boolean showHex = argList.remove("-hex");
235
236 if (argList.size() < 1) {
237 String version = ImageMetadataReader.class.getPackage().getImplementationVersion();
238 System.out.println("metadata-extractor version " + version);
239 System.out.println();
240 System.out.println(String.format("Usage: java -jar metadata-extractor-%s.jar <filename> [<filename>] [-thumb] [-markdown] [-hex]", version == null ? "a.b.c" : version));
241 System.exit(1);
242 }
243
244 for (String filePath : argList) {
245 long startTime = System.nanoTime();
246 File file = new File(filePath);
247
248 if (!markdownFormat && argList.size()>1)
249 System.out.printf("%n***** PROCESSING: %s%n%n", filePath);
250
251 Metadata metadata = null;
252 try {
253 metadata = ImageMetadataReader.readMetadata(file);
254 } catch (Exception e) {
255 e.printStackTrace(System.err);
256 System.exit(1);
257 }
258 long took = System.nanoTime() - startTime;
259 if (!markdownFormat)
260 System.out.printf("Processed %.3f MB file in %.2f ms%n%n", file.length() / (1024d * 1024), took / 1000000d);
261
262 if (markdownFormat) {
263 String fileName = file.getName();
264 String urlName = StringUtil.urlEncode(filePath);
265 ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
266 String make = exifIFD0Directory == null ? "" : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MAKE);
267 String model = exifIFD0Directory == null ? "" : exifIFD0Directory.getString(ExifIFD0Directory.TAG_MODEL);
268 System.out.println();
269 System.out.println("---");
270 System.out.println();
271 System.out.printf("# %s - %s%n", make, model);
272 System.out.println();
273 System.out.printf("<a href=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\">%n", urlName);
274 System.out.printf("<img src=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\" width=\"300\"/><br/>%n", urlName);
275 System.out.println(fileName);
276 System.out.println("</a>");
277 System.out.println();
278 System.out.println("Directory | Tag Id | Tag Name | Extracted Value");
279 System.out.println(":--------:|-------:|----------|----------------");
280 }
281
282 // iterate over the metadata and print to System.out
283 for (Directory directory : metadata.getDirectories()) {
284 String directoryName = directory.getName();
285 for (Tag tag : directory.getTags()) {
286 String tagName = tag.getTagName();
287 String description = tag.getDescription();
288
289 // truncate the description if it's too long
290 if (description != null && description.length() > 1024) {
291 description = description.substring(0, 1024) + "...";
292 }
293
294 if (markdownFormat) {
295 System.out.printf("%s|0x%s|%s|%s%n",
296 directoryName,
297 Integer.toHexString(tag.getTagType()),
298 tagName,
299 description);
300 } else {
301 // simple formatting
302 if (showHex) {
303 System.out.printf("[%s - %s] %s = %s%n", directoryName, tag.getTagTypeHex(), tagName, description);
304 } else {
305 System.out.printf("[%s] %s = %s%n", directoryName, tagName, description);
306 }
307 }
308 }
309
310 if (directory instanceof XmpDirectory) {
311 Map<String, String> xmpProperties = ((XmpDirectory)directory).getXmpProperties();
312 for (Map.Entry<String, String> property : xmpProperties.entrySet()) {
313 String key = property.getKey();
314 String value = property.getValue();
315
316 if (value != null && value.length() > 1024) {
317 value = value.substring(0, 1024) + "...";
318 }
319
320 if (markdownFormat) {
321 System.out.printf("%s||%s|%s%n", directoryName, key, value);
322 } else {
323 System.out.printf("[%s] %s = %s%n", directoryName, key, value);
324 }
325 }
326 }
327
328 // print out any errors
329 for (String error : directory.getErrors())
330 System.err.println("ERROR: " + error);
331 }
332 }
333 }
334 }