Debian Codegraph @

src/com/drew/imaging/png/PngMetadataReader.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.png;
22
23 import com.drew.imaging.tiff.TiffProcessingException;
24 import com.drew.imaging.tiff.TiffReader;
25 import com.drew.lang.*;
26 import com.drew.lang.annotations.NotNull;
27 import com.drew.metadata.ErrorDirectory;
28 import com.drew.metadata.Metadata;
29 import com.drew.metadata.StringValue;
30 import com.drew.metadata.exif.ExifTiffHandler;
31 import com.drew.metadata.file.FileSystemMetadataReader;
32 import com.drew.metadata.icc.IccReader;
33 import com.drew.metadata.png.PngChromaticitiesDirectory;
34 import com.drew.metadata.png.PngDirectory;
35 import com.drew.metadata.xmp.XmpReader;
36
37 import java.io.*;
38 import java.nio.charset.Charset;
39 import java.util.*;
40 import java.util.zip.InflaterInputStream;
41
42 /**
43 * @author Drew Noakes https://drewnoakes.com
44 */
45 public class PngMetadataReader
46 {
47 private static Set<PngChunkType> _desiredChunkTypes;
48
49 /**
50 * The PNG spec states that ISO_8859_1 (Latin-1) encoding should be used for:
51 * <ul>
52 * <li>"tEXt" and "zTXt" chunks, both for keys and values (https://www.w3.org/TR/PNG/#11tEXt)</li>
53 * <li>"iCCP" chunks, for the profile name (https://www.w3.org/TR/PNG/#11iCCP)</li>
54 * <li>"sPLT" chunks, for the palette name (https://www.w3.org/TR/PNG/#11sPLT)</li>
55 * </ul>
56 * Note that "iTXt" chunks use UTF-8 encoding (https://www.w3.org/TR/PNG/#11iTXt).
57 * <p/>
58 * For more guidance: http://www.w3.org/TR/PNG-Decoders.html#D.Text-chunk-processing
59 */
60 private static Charset _latin1Encoding = Charsets.ISO_8859_1;
61 private static Charset _utf8Encoding = Charsets.UTF_8;
62
63 static
64 {
65 Set<PngChunkType> desiredChunkTypes = new HashSet<PngChunkType>();
66
67 desiredChunkTypes.add(PngChunkType.IHDR);
68 desiredChunkTypes.add(PngChunkType.PLTE);
69 desiredChunkTypes.add(PngChunkType.tRNS);
70 desiredChunkTypes.add(PngChunkType.cHRM);
71 desiredChunkTypes.add(PngChunkType.sRGB);
72 desiredChunkTypes.add(PngChunkType.gAMA);
73 desiredChunkTypes.add(PngChunkType.iCCP);
74 desiredChunkTypes.add(PngChunkType.bKGD);
75 desiredChunkTypes.add(PngChunkType.tEXt);
76 desiredChunkTypes.add(PngChunkType.zTXt);
77 desiredChunkTypes.add(PngChunkType.iTXt);
78 desiredChunkTypes.add(PngChunkType.tIME);
79 desiredChunkTypes.add(PngChunkType.pHYs);
80 desiredChunkTypes.add(PngChunkType.sBIT);
81 desiredChunkTypes.add(PngChunkType.eXIf);
82
83 _desiredChunkTypes = Collections.unmodifiableSet(desiredChunkTypes);
84 }
85
86 @NotNull
87 public static Metadata readMetadata(@NotNull File file) throws PngProcessingException, IOException
88 {
89 InputStream inputStream = new FileInputStream(file);
90 Metadata metadata;
91 try {
92 metadata = readMetadata(inputStream);
93 } finally {
94 inputStream.close();
95 }
96 new FileSystemMetadataReader().read(file, metadata);
97 return metadata;
98 }
99
100 @NotNull
101 public static Metadata readMetadata(@NotNull InputStream inputStream) throws PngProcessingException, IOException
102 {
103 Iterable<PngChunk> chunks = new PngChunkReader().extract(new StreamReader(inputStream), _desiredChunkTypes);
104
105 Metadata metadata = new Metadata();
106
107 for (PngChunk chunk : chunks) {
108 try {
109 processChunk(metadata, chunk);
110 } catch (Exception e) {
111 metadata.addDirectory(new ErrorDirectory("Exception reading PNG chunk: " + e.getMessage()));
112 }
113 }
114
115 return metadata;
116 }
117
118 private static void processChunk(@NotNull Metadata metadata, @NotNull PngChunk chunk) throws PngProcessingException, IOException
119 {
120 PngChunkType chunkType = chunk.getType();
121 byte[] bytes = chunk.getBytes();
122
123 if (chunkType.equals(PngChunkType.IHDR)) {
124 PngHeader header = new PngHeader(bytes);
125 PngDirectory directory = new PngDirectory(PngChunkType.IHDR);
126 directory.setInt(PngDirectory.TAG_IMAGE_WIDTH, header.getImageWidth());
127 directory.setInt(PngDirectory.TAG_IMAGE_HEIGHT, header.getImageHeight());
128 directory.setInt(PngDirectory.TAG_BITS_PER_SAMPLE, header.getBitsPerSample());
129 directory.setInt(PngDirectory.TAG_COLOR_TYPE, header.getColorType().getNumericValue());
130 directory.setInt(PngDirectory.TAG_COMPRESSION_TYPE, header.getCompressionType() & 0xFF); // make sure it's unsigned
131 directory.setInt(PngDirectory.TAG_FILTER_METHOD, header.getFilterMethod());
132 directory.setInt(PngDirectory.TAG_INTERLACE_METHOD, header.getInterlaceMethod());
133 metadata.addDirectory(directory);
134 } else if (chunkType.equals(PngChunkType.PLTE)) {
135 PngDirectory directory = new PngDirectory(PngChunkType.PLTE);
136 directory.setInt(PngDirectory.TAG_PALETTE_SIZE, bytes.length / 3);
137 metadata.addDirectory(directory);
138 } else if (chunkType.equals(PngChunkType.tRNS)) {
139 PngDirectory directory = new PngDirectory(PngChunkType.tRNS);
140 directory.setInt(PngDirectory.TAG_PALETTE_HAS_TRANSPARENCY, 1);
141 metadata.addDirectory(directory);
142 } else if (chunkType.equals(PngChunkType.sRGB)) {
143 int srgbRenderingIntent = bytes[0];
144 PngDirectory directory = new PngDirectory(PngChunkType.sRGB);
145 directory.setInt(PngDirectory.TAG_SRGB_RENDERING_INTENT, srgbRenderingIntent);
146 metadata.addDirectory(directory);
147 } else if (chunkType.equals(PngChunkType.cHRM)) {
148 PngChromaticities chromaticities = new PngChromaticities(bytes);
149 PngChromaticitiesDirectory directory = new PngChromaticitiesDirectory();
150 directory.setInt(PngChromaticitiesDirectory.TAG_WHITE_POINT_X, chromaticities.getWhitePointX());
151 directory.setInt(PngChromaticitiesDirectory.TAG_WHITE_POINT_Y, chromaticities.getWhitePointY());
152 directory.setInt(PngChromaticitiesDirectory.TAG_RED_X, chromaticities.getRedX());
153 directory.setInt(PngChromaticitiesDirectory.TAG_RED_Y, chromaticities.getRedY());
154 directory.setInt(PngChromaticitiesDirectory.TAG_GREEN_X, chromaticities.getGreenX());
155 directory.setInt(PngChromaticitiesDirectory.TAG_GREEN_Y, chromaticities.getGreenY());
156 directory.setInt(PngChromaticitiesDirectory.TAG_BLUE_X, chromaticities.getBlueX());
157 directory.setInt(PngChromaticitiesDirectory.TAG_BLUE_Y, chromaticities.getBlueY());
158 metadata.addDirectory(directory);
159 } else if (chunkType.equals(PngChunkType.gAMA)) {
160 int gammaInt = ByteConvert.toInt32BigEndian(bytes);
161 new SequentialByteArrayReader(bytes).getInt32();
162 PngDirectory directory = new PngDirectory(PngChunkType.gAMA);
163 directory.setDouble(PngDirectory.TAG_GAMMA, gammaInt / 100000.0);
164 metadata.addDirectory(directory);
165 } else if (chunkType.equals(PngChunkType.iCCP)) {
166 SequentialReader reader = new SequentialByteArrayReader(bytes);
167
168 // Profile Name is 1-79 bytes, followed by the 1 byte null character
169 byte[] profileNameBytes = reader.getNullTerminatedBytes(79 + 1);
170 PngDirectory directory = new PngDirectory(PngChunkType.iCCP);
171 directory.setStringValue(PngDirectory.TAG_ICC_PROFILE_NAME, new StringValue(profileNameBytes, _latin1Encoding));
172 byte compressionMethod = reader.getInt8();
173 // Only compression method allowed by the spec is zero: deflate
174 if (compressionMethod == 0) {
175 // bytes left for compressed text is:
176 // total bytes length - (profilenamebytes length + null byte + compression method byte)
177 int bytesLeft = bytes.length - (profileNameBytes.length + 1 + 1);
178 byte[] compressedProfile = reader.getBytes(bytesLeft);
179
180 try {
181 InflaterInputStream inflateStream = new InflaterInputStream(new ByteArrayInputStream(compressedProfile));
182 new IccReader().extract(new RandomAccessStreamReader(inflateStream), metadata, directory);
183 inflateStream.close();
184 } catch(java.util.zip.ZipException zex) {
185 directory.addError(String.format("Exception decompressing PNG iCCP chunk : %s", zex.getMessage()));
186 metadata.addDirectory(directory);
187 }
188 } else {
189 directory.addError("Invalid compression method value");
190 }
191 metadata.addDirectory(directory);
192 } else if (chunkType.equals(PngChunkType.bKGD)) {
193 PngDirectory directory = new PngDirectory(PngChunkType.bKGD);
194 directory.setByteArray(PngDirectory.TAG_BACKGROUND_COLOR, bytes);
195 metadata.addDirectory(directory);
196 } else if (chunkType.equals(PngChunkType.tEXt)) {
197 SequentialReader reader = new SequentialByteArrayReader(bytes);
198
199 // Keyword is 1-79 bytes, followed by the 1 byte null character
200 StringValue keywordsv = reader.getNullTerminatedStringValue(79 + 1, _latin1Encoding);
201 String keyword = keywordsv.toString();
202
203 // bytes left for text is:
204 // total bytes length - (Keyword length + null byte)
205 int bytesLeft = bytes.length - (keywordsv.getBytes().length + 1);
206 StringValue value = reader.getNullTerminatedStringValue(bytesLeft, _latin1Encoding);
207 List<KeyValuePair> textPairs = new ArrayList<KeyValuePair>();
208 textPairs.add(new KeyValuePair(keyword, value));
209 PngDirectory directory = new PngDirectory(PngChunkType.tEXt);
210 directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs);
211 metadata.addDirectory(directory);
212 } else if (chunkType.equals(PngChunkType.zTXt)) {
213 SequentialReader reader = new SequentialByteArrayReader(bytes);
214
215 // Keyword is 1-79 bytes, followed by the 1 byte null character
216 StringValue keywordsv = reader.getNullTerminatedStringValue(79 + 1, _latin1Encoding);
217 String keyword = keywordsv.toString();
218 byte compressionMethod = reader.getInt8();
219
220 // bytes left for compressed text is:
221 // total bytes length - (Keyword length + null byte + compression method byte)
222 int bytesLeft = bytes.length - (keywordsv.getBytes().length + 1 + 1);
223 byte[] textBytes = null;
224 if (compressionMethod == 0) {
225 try {
226 textBytes = StreamUtil.readAllBytes(new InflaterInputStream(new ByteArrayInputStream(bytes, bytes.length - bytesLeft, bytesLeft)));
227 } catch(java.util.zip.ZipException zex) {
228 PngDirectory directory = new PngDirectory(PngChunkType.zTXt);
229 directory.addError(String.format("Exception decompressing PNG zTXt chunk with keyword \"%s\": %s", keyword, zex.getMessage()));
230 metadata.addDirectory(directory);
231 }
232 } else {
233 PngDirectory directory = new PngDirectory(PngChunkType.zTXt);
234 directory.addError("Invalid compression method value");
235 metadata.addDirectory(directory);
236 }
237 if (textBytes != null) {
238 if (keyword.equals("XML:com.adobe.xmp")) {
239 // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary
240 new XmpReader().extract(textBytes, metadata);
241 } else {
242 List<KeyValuePair> textPairs = new ArrayList<KeyValuePair>();
243 textPairs.add(new KeyValuePair(keyword, new StringValue(textBytes, _latin1Encoding)));
244 PngDirectory directory = new PngDirectory(PngChunkType.zTXt);
245 directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs);
246 metadata.addDirectory(directory);
247 }
248 }
249 } else if (chunkType.equals(PngChunkType.iTXt)) {
250 SequentialReader reader = new SequentialByteArrayReader(bytes);
251
252 // Keyword is 1-79 bytes, followed by the 1 byte null character
253 StringValue keywordsv = reader.getNullTerminatedStringValue(79 + 1, _utf8Encoding);
254 String keyword = keywordsv.toString();
255 byte compressionFlag = reader.getInt8();
256 byte compressionMethod = reader.getInt8();
257 // TODO we currently ignore languageTagBytes and translatedKeywordBytes
258 byte[] languageTagBytes = reader.getNullTerminatedBytes(bytes.length);
259 byte[] translatedKeywordBytes = reader.getNullTerminatedBytes(bytes.length);
260
261 // bytes left for compressed text is:
262 // total bytes length - (Keyword length + null byte + comp flag byte + comp method byte + lang length + null byte + translated length + null byte)
263 int bytesLeft = bytes.length - (keywordsv.getBytes().length + 1 + 1 + 1 + languageTagBytes.length + 1 + translatedKeywordBytes.length + 1);
264 byte[] textBytes = null;
265 if (compressionFlag == 0) {
266 textBytes = reader.getNullTerminatedBytes(bytesLeft);
267 } else if (compressionFlag == 1) {
268 if (compressionMethod == 0) {
269 try {
270 textBytes = StreamUtil.readAllBytes(new InflaterInputStream(new ByteArrayInputStream(bytes, bytes.length - bytesLeft, bytesLeft)));
271 } catch(java.util.zip.ZipException zex) {
272 PngDirectory directory = new PngDirectory(PngChunkType.iTXt);
273 directory.addError(String.format("Exception decompressing PNG iTXt chunk with keyword \"%s\": %s", keyword, zex.getMessage()));
274 metadata.addDirectory(directory);
275 }
276 } else {
277 PngDirectory directory = new PngDirectory(PngChunkType.iTXt);
278 directory.addError("Invalid compression method value");
279 metadata.addDirectory(directory);
280 }
281 } else {
282 PngDirectory directory = new PngDirectory(PngChunkType.iTXt);
283 directory.addError("Invalid compression flag value");
284 metadata.addDirectory(directory);
285 }
286
287 if (textBytes != null) {
288 if (keyword.equals("XML:com.adobe.xmp")) {
289 // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary
290 new XmpReader().extract(textBytes, metadata);
291 } else {
292 List<KeyValuePair> textPairs = new ArrayList<KeyValuePair>();
293 textPairs.add(new KeyValuePair(keyword, new StringValue(textBytes, _utf8Encoding)));
294 PngDirectory directory = new PngDirectory(PngChunkType.iTXt);
295 directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs);
296 metadata.addDirectory(directory);
297 }
298 }
299 } else if (chunkType.equals(PngChunkType.tIME)) {
300 SequentialByteArrayReader reader = new SequentialByteArrayReader(bytes);
301 int year = reader.getUInt16();
302 int month = reader.getUInt8();
303 int day = reader.getUInt8();
304 int hour = reader.getUInt8();
305 int minute = reader.getUInt8();
306 int second = reader.getUInt8();
307 PngDirectory directory = new PngDirectory(PngChunkType.tIME);
308 if (DateUtil.isValidDate(year, month - 1, day) && DateUtil.isValidTime(hour, minute, second)) {
309 String dateString = String.format("%04d:%02d:%02d %02d:%02d:%02d", year, month, day, hour, minute, second);
310 directory.setString(PngDirectory.TAG_LAST_MODIFICATION_TIME, dateString);
311 } else {
312 directory.addError(String.format(
313 "PNG tIME data describes an invalid date/time: year=%d month=%d day=%d hour=%d minute=%d second=%d",
314 year, month, day, hour, minute, second));
315 }
316 metadata.addDirectory(directory);
317 } else if (chunkType.equals(PngChunkType.pHYs)) {
318 SequentialByteArrayReader reader = new SequentialByteArrayReader(bytes);
319 int pixelsPerUnitX = reader.getInt32();
320 int pixelsPerUnitY = reader.getInt32();
321 byte unitSpecifier = reader.getInt8();
322 PngDirectory directory = new PngDirectory(PngChunkType.pHYs);
323 directory.setInt(PngDirectory.TAG_PIXELS_PER_UNIT_X, pixelsPerUnitX);
324 directory.setInt(PngDirectory.TAG_PIXELS_PER_UNIT_Y, pixelsPerUnitY);
325 directory.setInt(PngDirectory.TAG_UNIT_SPECIFIER, unitSpecifier);
326 metadata.addDirectory(directory);
327 } else if (chunkType.equals(PngChunkType.sBIT)) {
328 PngDirectory directory = new PngDirectory(PngChunkType.sBIT);
329 directory.setByteArray(PngDirectory.TAG_SIGNIFICANT_BITS, bytes);
330 metadata.addDirectory(directory);
331 } else if (chunkType.equals(PngChunkType.eXIf)) {
332 try {
333 ExifTiffHandler handler = new ExifTiffHandler(metadata, null, 0);
334 new TiffReader().processTiff(new ByteArrayReader(bytes), handler, 0);
335 } catch (TiffProcessingException ex) {
336 PngDirectory directory = new PngDirectory(PngChunkType.eXIf);
337 directory.addError(ex.getMessage());
338 metadata.addDirectory(directory);
339 } catch (IOException ex) {
340 PngDirectory directory = new PngDirectory(PngChunkType.eXIf);
341 directory.addError(ex.getMessage());
342 metadata.addDirectory(directory);
343 }
344 }
345 }
346 }