Debian Codegraph @

src/com/drew/metadata/bmp/BmpReader.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.bmp;
22
23 import com.drew.lang.ByteArrayReader;
24 import com.drew.lang.Charsets;
25 import com.drew.lang.SequentialReader;
26 import com.drew.lang.annotations.NotNull;
27 import com.drew.metadata.Directory;
28 import com.drew.metadata.ErrorDirectory;
29 import com.drew.metadata.Metadata;
30 import com.drew.metadata.MetadataException;
31 import com.drew.metadata.bmp.BmpHeaderDirectory.ColorSpaceType;
32 import com.drew.metadata.icc.IccReader;
33
34 import java.io.IOException;
35
36 /**
37 * Reader for Windows and OS/2 bitmap files.
38 * <p>
39 * References:
40 * <ul>
41 * <li><a href="https://web.archive.org/web/20170302205626/http://fileformats.archiveteam.org/wiki/BMP">Fileformats Wiki BMP overview</a></li>
42 * <li><a href="http://web.archive.org/web/20170303000822/http://netghost.narod.ru/gff/graphics/summary/micbmp.htm">Graphics File Formats encyclopedia Windows bitmap description</a></li>
43 * <li><a href="https://web.archive.org/web/20170302205330/http://netghost.narod.ru/gff/graphics/summary/os2bmp.htm">Graphics File Formats encyclopedia OS/2 bitmap description</a></li>
44 * <li><a href="https://web.archive.org/web/20170302205457/http://www.fileformat.info/format/os2bmp/spec/902d5c253f2a43ada39c2b81034f27fd/view.htm">OS/2 bitmap specification</a></li>
45 * <li><a href="https://msdn.microsoft.com/en-us/library/dd183392(v=vs.85).aspx">Microsoft Bitmap Structures</a></li>
46 * </ul>
47 *
48 * @author Drew Noakes https://drewnoakes.com
49 * @author Nadahar
50 */
51 public class BmpReader
52 {
53 // Possible "magic bytes" indicating bitmap type:
54 /**
55 * "BM" - Windows or OS/2 bitmap
56 */
57 public static final int BITMAP = 0x4D42;
58 /**
59 * "BA" - OS/2 Bitmap array (multiple bitmaps)
60 */
61 public static final int OS2_BITMAP_ARRAY = 0x4142;
62 /**
63 * "IC" - OS/2 Icon
64 */
65 public static final int OS2_ICON = 0x4349;
66 /**
67 * "CI" - OS/2 Color icon
68 */
69 public static final int OS2_COLOR_ICON = 0x4943;
70 /**
71 * "CP" - OS/2 Color pointer
72 */
73 public static final int OS2_COLOR_POINTER = 0x5043;
74 /**
75 * "PT" - OS/2 Pointer
76 */
77 public static final int OS2_POINTER = 0x5450;
78
79 public void extract(@NotNull final SequentialReader reader, final @NotNull Metadata metadata)
80 {
81 reader.setMotorolaByteOrder(false);
82
83 // BITMAP INFORMATION HEADER
84 //
85 // The first four bytes of the header give the size, which is a discriminator of the actual header format.
86 // See this for more information http://en.wikipedia.org/wiki/BMP_file_format
87
88 readFileHeader(reader, metadata, true);
89 }
90
91 protected void readFileHeader(@NotNull final SequentialReader reader, final @NotNull Metadata metadata, boolean allowArray) {
92 /*
93 * There are two possible headers a file can start with. If the magic
94 * number is OS/2 Bitmap Array (0x4142) the OS/2 Bitmap Array Header
95 * will follow. In all other cases the file header will follow, which
96 * is identical for Windows and OS/2.
97 *
98 * File header:
99 *
100 * WORD FileType; - File type identifier
101 * DWORD FileSize; - Size of the file in bytes
102 * WORD XHotSpot; - X coordinate of hotspot for pointers
103 * WORD YHotSpot; - Y coordinate of hotspot for pointers
104 * DWORD BitmapOffset; - Starting position of image data in bytes
105 *
106 * OS/2 Bitmap Array Header:
107 *
108 * WORD Type; - Header type, always 4142h ("BA")
109 * DWORD Size; - Size of this header
110 * DWORD OffsetToNext; - Offset to next OS2BMPARRAYFILEHEADER
111 * WORD ScreenWidth; - Width of the image display in pixels
112 * WORD ScreenHeight; - Height of the image display in pixels
113 *
114 */
115
116 final int magicNumber;
117 try {
118 magicNumber = reader.getUInt16();
119 } catch (IOException e) {
120 metadata.addDirectory(new ErrorDirectory("Couldn't determine bitmap type: " + e.getMessage()));
121 return;
122 }
123
124 Directory directory = null;
125 try {
126 switch (magicNumber) {
127 case OS2_BITMAP_ARRAY:
128 if (!allowArray) {
129 addError("Invalid bitmap file - nested arrays not allowed", metadata);
130 return;
131 }
132 reader.skip(4); // Size
133 long nextHeaderOffset = reader.getUInt32();
134 reader.skip(2 + 2); // Screen Resolution
135 readFileHeader(reader, metadata, false);
136 if (nextHeaderOffset == 0) {
137 return; // No more bitmaps
138 }
139 if (reader.getPosition() > nextHeaderOffset) {
140 addError("Invalid next header offset", metadata);
141 return;
142 }
143 reader.skip(nextHeaderOffset - reader.getPosition());
144 readFileHeader(reader, metadata, true);
145 break;
146 case BITMAP:
147 case OS2_ICON:
148 case OS2_COLOR_ICON:
149 case OS2_COLOR_POINTER:
150 case OS2_POINTER:
151 directory = new BmpHeaderDirectory();
152 metadata.addDirectory(directory);
153 directory.setInt(BmpHeaderDirectory.TAG_BITMAP_TYPE, magicNumber);
154 // skip past the rest of the file header
155 reader.skip(4 + 2 + 2 + 4);
156 readBitmapHeader(reader, (BmpHeaderDirectory) directory, metadata);
157 break;
158 default:
159 metadata.addDirectory(new ErrorDirectory("Invalid BMP magic number 0x" + Integer.toHexString(magicNumber)));
160 return;
161 }
162 } catch (IOException e) {
163 if (directory == null) {
164 addError("Unable to read BMP file header", metadata);
165 } else {
166 directory.addError("Unable to read BMP file header");
167 }
168 }
169 }
170
171 protected void readBitmapHeader(@NotNull final SequentialReader reader, final @NotNull BmpHeaderDirectory directory, final @NotNull Metadata metadata) {
172 /*
173 * BITMAPCOREHEADER (12 bytes):
174 *
175 * DWORD Size - Size of this header in bytes
176 * SHORT Width - Image width in pixels
177 * SHORT Height - Image height in pixels
178 * WORD Planes - Number of color planes
179 * WORD BitsPerPixel - Number of bits per pixel
180 *
181 * OS21XBITMAPHEADER (12 bytes):
182 *
183 * DWORD Size - Size of this structure in bytes
184 * WORD Width - Bitmap width in pixels
185 * WORD Height - Bitmap height in pixel
186 * WORD NumPlanes - Number of bit planes (color depth)
187 * WORD BitsPerPixel - Number of bits per pixel per plane
188 *
189 * OS22XBITMAPHEADER (16/64 bytes):
190 *
191 * DWORD Size - Size of this structure in bytes
192 * DWORD Width - Bitmap width in pixels
193 * DWORD Height - Bitmap height in pixel
194 * WORD NumPlanes - Number of bit planes (color depth)
195 * WORD BitsPerPixel - Number of bits per pixel per plane
196 *
197 * - Short version ends here -
198 *
199 * DWORD Compression - Bitmap compression scheme
200 * DWORD ImageDataSize - Size of bitmap data in bytes
201 * DWORD XResolution - X resolution of display device
202 * DWORD YResolution - Y resolution of display device
203 * DWORD ColorsUsed - Number of color table indices used
204 * DWORD ColorsImportant - Number of important color indices
205 * WORD Units - Type of units used to measure resolution
206 * WORD Reserved - Pad structure to 4-byte boundary
207 * WORD Recording - Recording algorithm
208 * WORD Rendering - Halftoning algorithm used
209 * DWORD Size1 - Reserved for halftoning algorithm use
210 * DWORD Size2 - Reserved for halftoning algorithm use
211 * DWORD ColorEncoding - Color model used in bitmap
212 * DWORD Identifier - Reserved for application use
213 *
214 * BITMAPINFOHEADER (40 bytes), BITMAPV2INFOHEADER (52 bytes), BITMAPV3INFOHEADER (56 bytes),
215 * BITMAPV4HEADER (108 bytes) and BITMAPV5HEADER (124 bytes):
216 *
217 * DWORD Size - Size of this header in bytes
218 * LONG Width - Image width in pixels
219 * LONG Height - Image height in pixels
220 * WORD Planes - Number of color planes
221 * WORD BitsPerPixel - Number of bits per pixel
222 * DWORD Compression - Compression methods used
223 * DWORD SizeOfBitmap - Size of bitmap in bytes
224 * LONG HorzResolution - Horizontal resolution in pixels per meter
225 * LONG VertResolution - Vertical resolution in pixels per meter
226 * DWORD ColorsUsed - Number of colors in the image
227 * DWORD ColorsImportant - Minimum number of important colors
228 *
229 * - BITMAPINFOHEADER ends here -
230 *
231 * DWORD RedMask - Mask identifying bits of red component
232 * DWORD GreenMask - Mask identifying bits of green component
233 * DWORD BlueMask - Mask identifying bits of blue component
234 *
235 * - BITMAPV2INFOHEADER ends here -
236 *
237 * DWORD AlphaMask - Mask identifying bits of alpha component
238 *
239 * - BITMAPV3INFOHEADER ends here -
240 *
241 * DWORD CSType - Color space type
242 * LONG RedX - X coordinate of red endpoint
243 * LONG RedY - Y coordinate of red endpoint
244 * LONG RedZ - Z coordinate of red endpoint
245 * LONG GreenX - X coordinate of green endpoint
246 * LONG GreenY - Y coordinate of green endpoint
247 * LONG GreenZ - Z coordinate of green endpoint
248 * LONG BlueX - X coordinate of blue endpoint
249 * LONG BlueY - Y coordinate of blue endpoint
250 * LONG BlueZ - Z coordinate of blue endpoint
251 * DWORD GammaRed - Gamma red coordinate scale value
252 * DWORD GammaGreen - Gamma green coordinate scale value
253 * DWORD GammaBlue - Gamma blue coordinate scale value
254 *
255 * - BITMAPV4HEADER ends here -
256 *
257 * DWORD Intent - Rendering intent for bitmap
258 * DWORD ProfileData - Offset of the profile data relative to BITMAPV5HEADER
259 * DWORD ProfileSize - Size, in bytes, of embedded profile data
260 * DWORD Reserved - Shall be zero
261 *
262 */
263
264 try {
265 int bitmapType = directory.getInt(BmpHeaderDirectory.TAG_BITMAP_TYPE);
266 long headerOffset = reader.getPosition();
267 int headerSize = reader.getInt32();
268
269 directory.setInt(BmpHeaderDirectory.TAG_HEADER_SIZE, headerSize);
270
271 /*
272 * Known header type sizes:
273 *
274 * 12 - BITMAPCOREHEADER or OS21XBITMAPHEADER
275 * 16 - OS22XBITMAPHEADER (short)
276 * 40 - BITMAPINFOHEADER
277 * 52 - BITMAPV2INFOHEADER
278 * 56 - BITMAPV3INFOHEADER
279 * 64 - OS22XBITMAPHEADER (full)
280 * 108 - BITMAPV4HEADER
281 * 124 - BITMAPV5HEADER
282 *
283 */
284
285 if (headerSize == 12 && bitmapType == BITMAP) { //BITMAPCOREHEADER
286 /*
287 * There's no way to tell BITMAPCOREHEADER and OS21XBITMAPHEADER
288 * apart for the "standard" bitmap type. The difference is only
289 * that BITMAPCOREHEADER has signed width and height while
290 * in OS21XBITMAPHEADER they are unsigned. Since BITMAPCOREHEADER,
291 * the Windows version, is most common, read them as signed.
292 */
293 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_WIDTH, reader.getInt16());
294 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_HEIGHT, reader.getInt16());
295 directory.setInt(BmpHeaderDirectory.TAG_COLOUR_PLANES, reader.getUInt16());
296 directory.setInt(BmpHeaderDirectory.TAG_BITS_PER_PIXEL, reader.getUInt16());
297 } else if (headerSize == 12) { // OS21XBITMAPHEADER
298 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_WIDTH, reader.getUInt16());
299 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_HEIGHT, reader.getUInt16());
300 directory.setInt(BmpHeaderDirectory.TAG_COLOUR_PLANES, reader.getUInt16());
301 directory.setInt(BmpHeaderDirectory.TAG_BITS_PER_PIXEL, reader.getUInt16());
302 } else if (headerSize == 16 || headerSize == 64) { // OS22XBITMAPHEADER
303 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_WIDTH, reader.getInt32());
304 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_HEIGHT, reader.getInt32());
305 directory.setInt(BmpHeaderDirectory.TAG_COLOUR_PLANES, reader.getUInt16());
306 directory.setInt(BmpHeaderDirectory.TAG_BITS_PER_PIXEL, reader.getUInt16());
307 if (headerSize > 16) {
308 directory.setInt(BmpHeaderDirectory.TAG_COMPRESSION, reader.getInt32());
309 reader.skip(4); // skip the pixel data length
310 directory.setInt(BmpHeaderDirectory.TAG_X_PIXELS_PER_METER, reader.getInt32());
311 directory.setInt(BmpHeaderDirectory.TAG_Y_PIXELS_PER_METER, reader.getInt32());
312 directory.setInt(BmpHeaderDirectory.TAG_PALETTE_COLOUR_COUNT, reader.getInt32());
313 directory.setInt(BmpHeaderDirectory.TAG_IMPORTANT_COLOUR_COUNT, reader.getInt32());
314 reader.skip(
315 2 + // Skip Units, can only be 0 (pixels per meter)
316 2 + // Skip padding
317 2 // Skip Recording, can only be 0 (left to right, bottom to top)
318 );
319 directory.setInt(BmpHeaderDirectory.TAG_RENDERING, reader.getUInt16());
320 reader.skip(4 + 4); // Skip Size1 and Size2
321 directory.setInt(BmpHeaderDirectory.TAG_COLOR_ENCODING, reader.getInt32());
322 reader.skip(4); // Skip Identifier
323 }
324 } else if (
325 headerSize == 40 || headerSize == 52 || headerSize == 56 ||
326 headerSize == 108 || headerSize == 124
327 ) { // BITMAPINFOHEADER V1-5
328 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_WIDTH, reader.getInt32());
329 directory.setInt(BmpHeaderDirectory.TAG_IMAGE_HEIGHT, reader.getInt32());
330 directory.setInt(BmpHeaderDirectory.TAG_COLOUR_PLANES, reader.getUInt16());
331 directory.setInt(BmpHeaderDirectory.TAG_BITS_PER_PIXEL, reader.getUInt16());
332 directory.setInt(BmpHeaderDirectory.TAG_COMPRESSION, reader.getInt32());
333 // skip the pixel data length
334 reader.skip(4);
335 directory.setInt(BmpHeaderDirectory.TAG_X_PIXELS_PER_METER, reader.getInt32());
336 directory.setInt(BmpHeaderDirectory.TAG_Y_PIXELS_PER_METER, reader.getInt32());
337 directory.setInt(BmpHeaderDirectory.TAG_PALETTE_COLOUR_COUNT, reader.getInt32());
338 directory.setInt(BmpHeaderDirectory.TAG_IMPORTANT_COLOUR_COUNT, reader.getInt32());
339 if (headerSize == 40) { // BITMAPINFOHEADER end
340 return;
341 }
342 directory.setLong(BmpHeaderDirectory.TAG_RED_MASK, reader.getUInt32());
343 directory.setLong(BmpHeaderDirectory.TAG_GREEN_MASK, reader.getUInt32());
344 directory.setLong(BmpHeaderDirectory.TAG_BLUE_MASK, reader.getUInt32());
345 if (headerSize == 52) { // BITMAPV2INFOHEADER end
346 return;
347 }
348 directory.setLong(BmpHeaderDirectory.TAG_ALPHA_MASK, reader.getUInt32());
349 if (headerSize == 56) { // BITMAPV3INFOHEADER end
350 return;
351 }
352 long csType = reader.getUInt32();
353 directory.setLong(BmpHeaderDirectory.TAG_COLOR_SPACE_TYPE, csType);
354 reader.skip(36); // Skip color endpoint coordinates
355 directory.setLong(BmpHeaderDirectory.TAG_GAMMA_RED, reader.getUInt32());
356 directory.setLong(BmpHeaderDirectory.TAG_GAMMA_GREEN, reader.getUInt32());
357 directory.setLong(BmpHeaderDirectory.TAG_GAMMA_BLUE, reader.getUInt32());
358 if (headerSize == 108) { // BITMAPV4HEADER end
359 return;
360 }
361 directory.setInt(BmpHeaderDirectory.TAG_INTENT, reader.getInt32());
362 if (csType == ColorSpaceType.PROFILE_EMBEDDED.getValue() || csType == ColorSpaceType.PROFILE_LINKED.getValue()) {
363 long profileOffset = reader.getUInt32();
364 int profileSize = reader.getInt32();
365 if (profileSize < 0) {
366 directory.addError("Invalid profile size " + profileSize);
367 return;
368 }
369 if (reader.getPosition() > headerOffset + profileOffset) {
370 directory.addError("Invalid profile data offset 0x" + Long.toHexString(headerOffset + profileOffset));
371 return;
372 }
373 reader.skip(headerOffset + profileOffset - reader.getPosition());
374 if (csType == ColorSpaceType.PROFILE_LINKED.getValue()) {
375 directory.setString(BmpHeaderDirectory.TAG_LINKED_PROFILE, reader.getNullTerminatedString(profileSize, Charsets.WINDOWS_1252));
376 } else {
377 ByteArrayReader randomAccessReader = new ByteArrayReader(reader.getBytes(profileSize));
378 new IccReader().extract(randomAccessReader, metadata, directory);
379 }
380 } else {
381 reader.skip(
382 4 + // Skip ProfileData offset
383 4 + // Skip ProfileSize
384 4 // Skip Reserved
385 );
386 }
387 } else {
388 directory.addError("Unexpected DIB header size: " + headerSize);
389 }
390 } catch (IOException e) {
391 directory.addError("Unable to read BMP header");
392 } catch (MetadataException e) {
393 directory.addError("Internal error");
394 }
395 }
396
397 protected void addError(@NotNull String errorMessage, final @NotNull Metadata metadata) {
398 ErrorDirectory directory = metadata.getFirstDirectoryOfType(ErrorDirectory.class);
399 if (directory == null) {
400 metadata.addDirectory(new ErrorDirectory(errorMessage));
401 } else {
402 directory.addError(errorMessage);
403 }
404 }
405 }