ExifInterface.java revision 473201868c0cb6d6fef4550c7aeb9c1ba7432d98
1/* 2 * Copyright (C) 2007 The Android Open Source Project 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 17package android.media; 18 19import android.annotation.NonNull; 20import android.content.res.AssetManager; 21import android.graphics.Bitmap; 22import android.graphics.BitmapFactory; 23import android.system.ErrnoException; 24import android.system.Os; 25import android.system.OsConstants; 26import android.util.Log; 27import android.util.Pair; 28import android.annotation.IntDef; 29 30import java.io.BufferedInputStream; 31import java.io.ByteArrayInputStream; 32import java.io.DataInputStream; 33import java.io.DataInput; 34import java.io.EOFException; 35import java.io.File; 36import java.io.FileDescriptor; 37import java.io.FileInputStream; 38import java.io.FileNotFoundException; 39import java.io.FileOutputStream; 40import java.io.FilterOutputStream; 41import java.io.IOException; 42import java.io.InputStream; 43import java.io.OutputStream; 44import java.nio.ByteBuffer; 45import java.nio.ByteOrder; 46import java.nio.charset.Charset; 47import java.nio.charset.StandardCharsets; 48import java.text.ParsePosition; 49import java.text.SimpleDateFormat; 50import java.util.Arrays; 51import java.util.LinkedList; 52import java.util.Date; 53import java.util.HashMap; 54import java.util.HashSet; 55import java.util.Map; 56import java.util.Set; 57import java.util.TimeZone; 58import java.util.regex.Matcher; 59import java.util.regex.Pattern; 60import java.lang.annotation.Retention; 61import java.lang.annotation.RetentionPolicy; 62 63import libcore.io.IoUtils; 64import libcore.io.Streams; 65 66/** 67 * This is a class for reading and writing Exif tags in a JPEG file or a RAW image file. 68 * <p> 69 * Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW and RAF. 70 * <p> 71 * Attribute mutation is supported for JPEG image files. 72 */ 73public class ExifInterface { 74 private static final String TAG = "ExifInterface"; 75 private static final boolean DEBUG = false; 76 77 // The Exif tag names. See Tiff 6.0 Section 3 and Section 8. 78 /** Type is String. */ 79 public static final String TAG_ARTIST = "Artist"; 80 /** Type is int. */ 81 public static final String TAG_BITS_PER_SAMPLE = "BitsPerSample"; 82 /** Type is int. */ 83 public static final String TAG_COMPRESSION = "Compression"; 84 /** Type is String. */ 85 public static final String TAG_COPYRIGHT = "Copyright"; 86 /** Type is String. */ 87 public static final String TAG_DATETIME = "DateTime"; 88 /** Type is String. */ 89 public static final String TAG_IMAGE_DESCRIPTION = "ImageDescription"; 90 /** Type is int. */ 91 public static final String TAG_IMAGE_LENGTH = "ImageLength"; 92 /** Type is int. */ 93 public static final String TAG_IMAGE_WIDTH = "ImageWidth"; 94 /** Type is int. */ 95 public static final String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat"; 96 /** Type is int. */ 97 public static final String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength"; 98 /** Type is String. */ 99 public static final String TAG_MAKE = "Make"; 100 /** Type is String. */ 101 public static final String TAG_MODEL = "Model"; 102 /** Type is int. */ 103 public static final String TAG_ORIENTATION = "Orientation"; 104 /** Type is int. */ 105 public static final String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation"; 106 /** Type is int. */ 107 public static final String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration"; 108 /** Type is rational. */ 109 public static final String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities"; 110 /** Type is rational. */ 111 public static final String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite"; 112 /** Type is int. */ 113 public static final String TAG_RESOLUTION_UNIT = "ResolutionUnit"; 114 /** Type is int. */ 115 public static final String TAG_ROWS_PER_STRIP = "RowsPerStrip"; 116 /** Type is int. */ 117 public static final String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel"; 118 /** Type is String. */ 119 public static final String TAG_SOFTWARE = "Software"; 120 /** Type is int. */ 121 public static final String TAG_STRIP_BYTE_COUNTS = "StripByteCounts"; 122 /** Type is int. */ 123 public static final String TAG_STRIP_OFFSETS = "StripOffsets"; 124 /** Type is int. */ 125 public static final String TAG_TRANSFER_FUNCTION = "TransferFunction"; 126 /** Type is rational. */ 127 public static final String TAG_WHITE_POINT = "WhitePoint"; 128 /** Type is rational. */ 129 public static final String TAG_X_RESOLUTION = "XResolution"; 130 /** Type is rational. */ 131 public static final String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients"; 132 /** Type is int. */ 133 public static final String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning"; 134 /** Type is int. */ 135 public static final String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling"; 136 /** Type is rational. */ 137 public static final String TAG_Y_RESOLUTION = "YResolution"; 138 /** Type is rational. */ 139 public static final String TAG_APERTURE_VALUE = "ApertureValue"; 140 /** Type is rational. */ 141 public static final String TAG_BRIGHTNESS_VALUE = "BrightnessValue"; 142 /** Type is String. */ 143 public static final String TAG_CFA_PATTERN = "CFAPattern"; 144 /** Type is int. */ 145 public static final String TAG_COLOR_SPACE = "ColorSpace"; 146 /** Type is String. */ 147 public static final String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration"; 148 /** Type is rational. */ 149 public static final String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel"; 150 /** Type is int. */ 151 public static final String TAG_CONTRAST = "Contrast"; 152 /** Type is int. */ 153 public static final String TAG_CUSTOM_RENDERED = "CustomRendered"; 154 /** Type is String. */ 155 public static final String TAG_DATETIME_DIGITIZED = "DateTimeDigitized"; 156 /** Type is String. */ 157 public static final String TAG_DATETIME_ORIGINAL = "DateTimeOriginal"; 158 /** Type is String. */ 159 public static final String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription"; 160 /** Type is double. */ 161 public static final String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio"; 162 /** Type is String. */ 163 public static final String TAG_EXIF_VERSION = "ExifVersion"; 164 /** Type is double. */ 165 public static final String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue"; 166 /** Type is rational. */ 167 public static final String TAG_EXPOSURE_INDEX = "ExposureIndex"; 168 /** Type is int. */ 169 public static final String TAG_EXPOSURE_MODE = "ExposureMode"; 170 /** Type is int. */ 171 public static final String TAG_EXPOSURE_PROGRAM = "ExposureProgram"; 172 /** Type is double. */ 173 public static final String TAG_EXPOSURE_TIME = "ExposureTime"; 174 /** Type is double. */ 175 public static final String TAG_F_NUMBER = "FNumber"; 176 /** 177 * Type is double. 178 * 179 * @deprecated use {@link #TAG_F_NUMBER} instead 180 */ 181 @Deprecated 182 public static final String TAG_APERTURE = "FNumber"; 183 /** Type is String. */ 184 public static final String TAG_FILE_SOURCE = "FileSource"; 185 /** Type is int. */ 186 public static final String TAG_FLASH = "Flash"; 187 /** Type is rational. */ 188 public static final String TAG_FLASH_ENERGY = "FlashEnergy"; 189 /** Type is String. */ 190 public static final String TAG_FLASHPIX_VERSION = "FlashpixVersion"; 191 /** Type is rational. */ 192 public static final String TAG_FOCAL_LENGTH = "FocalLength"; 193 /** Type is int. */ 194 public static final String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm"; 195 /** Type is int. */ 196 public static final String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit"; 197 /** Type is rational. */ 198 public static final String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution"; 199 /** Type is rational. */ 200 public static final String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution"; 201 /** Type is int. */ 202 public static final String TAG_GAIN_CONTROL = "GainControl"; 203 /** Type is int. */ 204 public static final String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings"; 205 /** 206 * Type is int. 207 * 208 * @deprecated use {@link #TAG_ISO_SPEED_RATINGS} instead 209 */ 210 @Deprecated 211 public static final String TAG_ISO = "ISOSpeedRatings"; 212 /** Type is String. */ 213 public static final String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID"; 214 /** Type is int. */ 215 public static final String TAG_LIGHT_SOURCE = "LightSource"; 216 /** Type is String. */ 217 public static final String TAG_MAKER_NOTE = "MakerNote"; 218 /** Type is rational. */ 219 public static final String TAG_MAX_APERTURE_VALUE = "MaxApertureValue"; 220 /** Type is int. */ 221 public static final String TAG_METERING_MODE = "MeteringMode"; 222 /** Type is int. */ 223 public static final String TAG_NEW_SUBFILE_TYPE = "NewSubfileType"; 224 /** Type is String. */ 225 public static final String TAG_OECF = "OECF"; 226 /** Type is int. */ 227 public static final String TAG_PIXEL_X_DIMENSION = "PixelXDimension"; 228 /** Type is int. */ 229 public static final String TAG_PIXEL_Y_DIMENSION = "PixelYDimension"; 230 /** Type is String. */ 231 public static final String TAG_RELATED_SOUND_FILE = "RelatedSoundFile"; 232 /** Type is int. */ 233 public static final String TAG_SATURATION = "Saturation"; 234 /** Type is int. */ 235 public static final String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType"; 236 /** Type is String. */ 237 public static final String TAG_SCENE_TYPE = "SceneType"; 238 /** Type is int. */ 239 public static final String TAG_SENSING_METHOD = "SensingMethod"; 240 /** Type is int. */ 241 public static final String TAG_SHARPNESS = "Sharpness"; 242 /** Type is rational. */ 243 public static final String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue"; 244 /** Type is String. */ 245 public static final String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse"; 246 /** Type is String. */ 247 public static final String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity"; 248 /** Type is int. */ 249 public static final String TAG_SUBFILE_TYPE = "SubfileType"; 250 /** Type is String. */ 251 public static final String TAG_SUBSEC_TIME = "SubSecTime"; 252 /** 253 * Type is String. 254 * 255 * @deprecated use {@link #TAG_SUBSEC_TIME_DIGITIZED} instead 256 */ 257 public static final String TAG_SUBSEC_TIME_DIG = "SubSecTimeDigitized"; 258 /** Type is String. */ 259 public static final String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized"; 260 /** 261 * Type is String. 262 * 263 * @deprecated use {@link #TAG_SUBSEC_TIME_ORIGINAL} instead 264 */ 265 public static final String TAG_SUBSEC_TIME_ORIG = "SubSecTimeOriginal"; 266 /** Type is String. */ 267 public static final String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal"; 268 /** Type is int. */ 269 public static final String TAG_SUBJECT_AREA = "SubjectArea"; 270 /** Type is double. */ 271 public static final String TAG_SUBJECT_DISTANCE = "SubjectDistance"; 272 /** Type is int. */ 273 public static final String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange"; 274 /** Type is int. */ 275 public static final String TAG_SUBJECT_LOCATION = "SubjectLocation"; 276 /** Type is String. */ 277 public static final String TAG_USER_COMMENT = "UserComment"; 278 /** Type is int. */ 279 public static final String TAG_WHITE_BALANCE = "WhiteBalance"; 280 /** 281 * The altitude (in meters) based on the reference in TAG_GPS_ALTITUDE_REF. 282 * Type is rational. 283 */ 284 public static final String TAG_GPS_ALTITUDE = "GPSAltitude"; 285 /** 286 * 0 if the altitude is above sea level. 1 if the altitude is below sea 287 * level. Type is int. 288 */ 289 public static final String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef"; 290 /** Type is String. */ 291 public static final String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation"; 292 /** Type is rational. */ 293 public static final String TAG_GPS_DOP = "GPSDOP"; 294 /** Type is String. */ 295 public static final String TAG_GPS_DATESTAMP = "GPSDateStamp"; 296 /** Type is rational. */ 297 public static final String TAG_GPS_DEST_BEARING = "GPSDestBearing"; 298 /** Type is String. */ 299 public static final String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef"; 300 /** Type is rational. */ 301 public static final String TAG_GPS_DEST_DISTANCE = "GPSDestDistance"; 302 /** Type is String. */ 303 public static final String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef"; 304 /** Type is rational. */ 305 public static final String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude"; 306 /** Type is String. */ 307 public static final String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef"; 308 /** Type is rational. */ 309 public static final String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude"; 310 /** Type is String. */ 311 public static final String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef"; 312 /** Type is int. */ 313 public static final String TAG_GPS_DIFFERENTIAL = "GPSDifferential"; 314 /** Type is rational. */ 315 public static final String TAG_GPS_IMG_DIRECTION = "GPSImgDirection"; 316 /** Type is String. */ 317 public static final String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef"; 318 /** Type is rational. Format is "num1/denom1,num2/denom2,num3/denom3". */ 319 public static final String TAG_GPS_LATITUDE = "GPSLatitude"; 320 /** Type is String. */ 321 public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef"; 322 /** Type is rational. Format is "num1/denom1,num2/denom2,num3/denom3". */ 323 public static final String TAG_GPS_LONGITUDE = "GPSLongitude"; 324 /** Type is String. */ 325 public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef"; 326 /** Type is String. */ 327 public static final String TAG_GPS_MAP_DATUM = "GPSMapDatum"; 328 /** Type is String. */ 329 public static final String TAG_GPS_MEASURE_MODE = "GPSMeasureMode"; 330 /** Type is String. Name of GPS processing method used for location finding. */ 331 public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod"; 332 /** Type is String. */ 333 public static final String TAG_GPS_SATELLITES = "GPSSatellites"; 334 /** Type is rational. */ 335 public static final String TAG_GPS_SPEED = "GPSSpeed"; 336 /** Type is String. */ 337 public static final String TAG_GPS_SPEED_REF = "GPSSpeedRef"; 338 /** Type is String. */ 339 public static final String TAG_GPS_STATUS = "GPSStatus"; 340 /** Type is String. Format is "hh:mm:ss". */ 341 public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp"; 342 /** Type is rational. */ 343 public static final String TAG_GPS_TRACK = "GPSTrack"; 344 /** Type is String. */ 345 public static final String TAG_GPS_TRACK_REF = "GPSTrackRef"; 346 /** Type is String. */ 347 public static final String TAG_GPS_VERSION_ID = "GPSVersionID"; 348 /** Type is String. */ 349 public static final String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex"; 350 /** Type is int. */ 351 public static final String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength"; 352 /** Type is int. */ 353 public static final String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth"; 354 /** Type is int. DNG Specification 1.4.0.0. Section 4 */ 355 public static final String TAG_DNG_VERSION = "DNGVersion"; 356 /** Type is int. DNG Specification 1.4.0.0. Section 4 */ 357 public static final String TAG_DEFAULT_CROP_SIZE = "DefaultCropSize"; 358 /** Type is undefined. See Olympus MakerNote tags in http://www.exiv2.org/tags-olympus.html. */ 359 public static final String TAG_ORF_THUMBNAIL_IMAGE = "ThumbnailImage"; 360 /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */ 361 public static final String TAG_ORF_PREVIEW_IMAGE_START = "PreviewImageStart"; 362 /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */ 363 public static final String TAG_ORF_PREVIEW_IMAGE_LENGTH = "PreviewImageLength"; 364 /** Type is int. See Olympus Image Processing tags in http://www.exiv2.org/tags-olympus.html. */ 365 public static final String TAG_ORF_ASPECT_FRAME = "AspectFrame"; 366 /** 367 * Type is int. See PanasonicRaw tags in 368 * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html 369 */ 370 public static final String TAG_RW2_SENSOR_BOTTOM_BORDER = "SensorBottomBorder"; 371 /** 372 * Type is int. See PanasonicRaw tags in 373 * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html 374 */ 375 public static final String TAG_RW2_SENSOR_LEFT_BORDER = "SensorLeftBorder"; 376 /** 377 * Type is int. See PanasonicRaw tags in 378 * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html 379 */ 380 public static final String TAG_RW2_SENSOR_RIGHT_BORDER = "SensorRightBorder"; 381 /** 382 * Type is int. See PanasonicRaw tags in 383 * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html 384 */ 385 public static final String TAG_RW2_SENSOR_TOP_BORDER = "SensorTopBorder"; 386 /** 387 * Type is int. See PanasonicRaw tags in 388 * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html 389 */ 390 public static final String TAG_RW2_ISO = "ISO"; 391 /** 392 * Type is undefined. See PanasonicRaw tags in 393 * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html 394 */ 395 public static final String TAG_RW2_JPG_FROM_RAW = "JpgFromRaw"; 396 397 /** 398 * Private tags used for pointing the other IFD offsets. 399 * The types of the following tags are int. 400 * See JEITA CP-3451C Section 4.6.3: Exif-specific IFD. 401 * For SubIFD, see Note 1 of Adobe PageMaker® 6.0 TIFF Technical Notes. 402 */ 403 private static final String TAG_EXIF_IFD_POINTER = "ExifIFDPointer"; 404 private static final String TAG_GPS_INFO_IFD_POINTER = "GPSInfoIFDPointer"; 405 private static final String TAG_INTEROPERABILITY_IFD_POINTER = "InteroperabilityIFDPointer"; 406 private static final String TAG_SUB_IFD_POINTER = "SubIFDPointer"; 407 // Proprietary pointer tags used for ORF files. 408 // See http://www.exiv2.org/tags-olympus.html 409 private static final String TAG_ORF_CAMERA_SETTINGS_IFD_POINTER = "CameraSettingsIFDPointer"; 410 private static final String TAG_ORF_IMAGE_PROCESSING_IFD_POINTER = "ImageProcessingIFDPointer"; 411 412 // Private tags used for thumbnail information. 413 private static final String TAG_HAS_THUMBNAIL = "HasThumbnail"; 414 private static final String TAG_THUMBNAIL_OFFSET = "ThumbnailOffset"; 415 private static final String TAG_THUMBNAIL_LENGTH = "ThumbnailLength"; 416 private static final String TAG_THUMBNAIL_DATA = "ThumbnailData"; 417 private static final int MAX_THUMBNAIL_SIZE = 512; 418 419 // Constants used for the Orientation Exif tag. 420 public static final int ORIENTATION_UNDEFINED = 0; 421 public static final int ORIENTATION_NORMAL = 1; 422 public static final int ORIENTATION_FLIP_HORIZONTAL = 2; // left right reversed mirror 423 public static final int ORIENTATION_ROTATE_180 = 3; 424 public static final int ORIENTATION_FLIP_VERTICAL = 4; // upside down mirror 425 // flipped about top-left <--> bottom-right axis 426 public static final int ORIENTATION_TRANSPOSE = 5; 427 public static final int ORIENTATION_ROTATE_90 = 6; // rotate 90 cw to right it 428 // flipped about top-right <--> bottom-left axis 429 public static final int ORIENTATION_TRANSVERSE = 7; 430 public static final int ORIENTATION_ROTATE_270 = 8; // rotate 270 to right it 431 432 // Constants used for white balance 433 public static final int WHITEBALANCE_AUTO = 0; 434 public static final int WHITEBALANCE_MANUAL = 1; 435 436 // Maximum size for checking file type signature (see image_type_recognition_lite.cc) 437 private static final int SIGNATURE_CHECK_SIZE = 5000; 438 439 private static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff}; 440 private static final String RAF_SIGNATURE = "FUJIFILMCCD-RAW"; 441 private static final int RAF_OFFSET_TO_JPEG_IMAGE_OFFSET = 84; 442 private static final int RAF_INFO_SIZE = 160; 443 private static final int RAF_JPEG_LENGTH_VALUE_SIZE = 4; 444 445 private static final byte[] HEIF_TYPE_FTYP = new byte[] {'f', 't', 'y', 'p'}; 446 private static final byte[] HEIF_BRAND_MIF1 = new byte[] {'m', 'i', 'f', '1'}; 447 private static final byte[] HEIF_BRAND_HEIC = new byte[] {'h', 'e', 'i', 'c'}; 448 449 // See http://fileformats.archiveteam.org/wiki/Olympus_ORF 450 private static final short ORF_SIGNATURE_1 = 0x4f52; 451 private static final short ORF_SIGNATURE_2 = 0x5352; 452 // There are two formats for Olympus Makernote Headers. Each has different identifiers and 453 // offsets to the actual data. 454 // See http://www.exiv2.org/makernote.html#R1 455 private static final byte[] ORF_MAKER_NOTE_HEADER_1 = new byte[] {(byte) 0x4f, (byte) 0x4c, 456 (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x00}; // "OLYMP\0" 457 private static final byte[] ORF_MAKER_NOTE_HEADER_2 = new byte[] {(byte) 0x4f, (byte) 0x4c, 458 (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x55, (byte) 0x53, (byte) 0x00, 459 (byte) 0x49, (byte) 0x49}; // "OLYMPUS\0II" 460 private static final int ORF_MAKER_NOTE_HEADER_1_SIZE = 8; 461 private static final int ORF_MAKER_NOTE_HEADER_2_SIZE = 12; 462 463 // See http://fileformats.archiveteam.org/wiki/RW2 464 private static final short RW2_SIGNATURE = 0x0055; 465 466 // See http://fileformats.archiveteam.org/wiki/Pentax_PEF 467 private static final String PEF_SIGNATURE = "PENTAX"; 468 // See http://www.exiv2.org/makernote.html#R11 469 private static final int PEF_MAKER_NOTE_SKIP_SIZE = 6; 470 471 private static SimpleDateFormat sFormatter; 472 473 // See Exchangeable image file format for digital still cameras: Exif version 2.2. 474 // The following values are for parsing EXIF data area. There are tag groups in EXIF data area. 475 // They are called "Image File Directory". They have multiple data formats to cover various 476 // image metadata from GPS longitude to camera model name. 477 478 // Types of Exif byte alignments (see JEITA CP-3451C Section 4.5.2) 479 private static final short BYTE_ALIGN_II = 0x4949; // II: Intel order 480 private static final short BYTE_ALIGN_MM = 0x4d4d; // MM: Motorola order 481 482 // TIFF Header Fixed Constant (see JEITA CP-3451C Section 4.5.2) 483 private static final byte START_CODE = 0x2a; // 42 484 private static final int IFD_OFFSET = 8; 485 486 // Formats for the value in IFD entry (See TIFF 6.0 Section 2, "Image File Directory".) 487 private static final int IFD_FORMAT_BYTE = 1; 488 private static final int IFD_FORMAT_STRING = 2; 489 private static final int IFD_FORMAT_USHORT = 3; 490 private static final int IFD_FORMAT_ULONG = 4; 491 private static final int IFD_FORMAT_URATIONAL = 5; 492 private static final int IFD_FORMAT_SBYTE = 6; 493 private static final int IFD_FORMAT_UNDEFINED = 7; 494 private static final int IFD_FORMAT_SSHORT = 8; 495 private static final int IFD_FORMAT_SLONG = 9; 496 private static final int IFD_FORMAT_SRATIONAL = 10; 497 private static final int IFD_FORMAT_SINGLE = 11; 498 private static final int IFD_FORMAT_DOUBLE = 12; 499 // Format indicating a new IFD entry (See Adobe PageMaker® 6.0 TIFF Technical Notes, "New Tag") 500 private static final int IFD_FORMAT_IFD = 13; 501 // Names for the data formats for debugging purpose. 502 private static final String[] IFD_FORMAT_NAMES = new String[] { 503 "", "BYTE", "STRING", "USHORT", "ULONG", "URATIONAL", "SBYTE", "UNDEFINED", "SSHORT", 504 "SLONG", "SRATIONAL", "SINGLE", "DOUBLE" 505 }; 506 // Sizes of the components of each IFD value format 507 private static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] { 508 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1 509 }; 510 private static final byte[] EXIF_ASCII_PREFIX = new byte[] { 511 0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0 512 }; 513 514 /** 515 * Constants used for Compression tag. 516 * For Value 1, 2, 32773, see TIFF 6.0 Spec Section 3: Bilevel Images, Compression 517 * For Value 6, see TIFF 6.0 Spec Section 22: JPEG Compression, Extensions to Existing Fields 518 * For Value 7, 8, 34892, see DNG Specification 1.4.0.0. Section 3, Compression 519 */ 520 private static final int DATA_UNCOMPRESSED = 1; 521 private static final int DATA_HUFFMAN_COMPRESSED = 2; 522 private static final int DATA_JPEG = 6; 523 private static final int DATA_JPEG_COMPRESSED = 7; 524 private static final int DATA_DEFLATE_ZIP = 8; 525 private static final int DATA_PACK_BITS_COMPRESSED = 32773; 526 private static final int DATA_LOSSY_JPEG = 34892; 527 528 /** 529 * Constants used for BitsPerSample tag. 530 * For RGB, see TIFF 6.0 Spec Section 6, Differences from Palette Color Images 531 * For Greyscale, see TIFF 6.0 Spec Section 4, Differences from Bilevel Images 532 */ 533 private static final int[] BITS_PER_SAMPLE_RGB = new int[] { 8, 8, 8 }; 534 private static final int[] BITS_PER_SAMPLE_GREYSCALE_1 = new int[] { 4 }; 535 private static final int[] BITS_PER_SAMPLE_GREYSCALE_2 = new int[] { 8 }; 536 537 /** 538 * Constants used for PhotometricInterpretation tag. 539 * For White/Black, see Section 3, Color. 540 * See TIFF 6.0 Spec Section 22, Minimum Requirements for TIFF with JPEG Compression. 541 */ 542 private static final int PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO = 0; 543 private static final int PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO = 1; 544 private static final int PHOTOMETRIC_INTERPRETATION_RGB = 2; 545 private static final int PHOTOMETRIC_INTERPRETATION_YCBCR = 6; 546 547 /** 548 * Constants used for NewSubfileType tag. 549 * See TIFF 6.0 Spec Section 8 550 * */ 551 private static final int ORIGINAL_RESOLUTION_IMAGE = 0; 552 private static final int REDUCED_RESOLUTION_IMAGE = 1; 553 554 // A class for indicating EXIF rational type. 555 private static class Rational { 556 public final long numerator; 557 public final long denominator; 558 559 private Rational(long numerator, long denominator) { 560 // Handle erroneous case 561 if (denominator == 0) { 562 this.numerator = 0; 563 this.denominator = 1; 564 return; 565 } 566 this.numerator = numerator; 567 this.denominator = denominator; 568 } 569 570 @Override 571 public String toString() { 572 return numerator + "/" + denominator; 573 } 574 575 public double calculate() { 576 return (double) numerator / denominator; 577 } 578 } 579 580 // A class for indicating EXIF attribute. 581 private static class ExifAttribute { 582 public final int format; 583 public final int numberOfComponents; 584 public final byte[] bytes; 585 586 private ExifAttribute(int format, int numberOfComponents, byte[] bytes) { 587 this.format = format; 588 this.numberOfComponents = numberOfComponents; 589 this.bytes = bytes; 590 } 591 592 public static ExifAttribute createUShort(int[] values, ByteOrder byteOrder) { 593 final ByteBuffer buffer = ByteBuffer.wrap( 594 new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_USHORT] * values.length]); 595 buffer.order(byteOrder); 596 for (int value : values) { 597 buffer.putShort((short) value); 598 } 599 return new ExifAttribute(IFD_FORMAT_USHORT, values.length, buffer.array()); 600 } 601 602 public static ExifAttribute createUShort(int value, ByteOrder byteOrder) { 603 return createUShort(new int[] {value}, byteOrder); 604 } 605 606 public static ExifAttribute createULong(long[] values, ByteOrder byteOrder) { 607 final ByteBuffer buffer = ByteBuffer.wrap( 608 new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_ULONG] * values.length]); 609 buffer.order(byteOrder); 610 for (long value : values) { 611 buffer.putInt((int) value); 612 } 613 return new ExifAttribute(IFD_FORMAT_ULONG, values.length, buffer.array()); 614 } 615 616 public static ExifAttribute createULong(long value, ByteOrder byteOrder) { 617 return createULong(new long[] {value}, byteOrder); 618 } 619 620 public static ExifAttribute createSLong(int[] values, ByteOrder byteOrder) { 621 final ByteBuffer buffer = ByteBuffer.wrap( 622 new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SLONG] * values.length]); 623 buffer.order(byteOrder); 624 for (int value : values) { 625 buffer.putInt(value); 626 } 627 return new ExifAttribute(IFD_FORMAT_SLONG, values.length, buffer.array()); 628 } 629 630 public static ExifAttribute createSLong(int value, ByteOrder byteOrder) { 631 return createSLong(new int[] {value}, byteOrder); 632 } 633 634 public static ExifAttribute createByte(String value) { 635 // Exception for GPSAltitudeRef tag 636 if (value.length() == 1 && value.charAt(0) >= '0' && value.charAt(0) <= '1') { 637 final byte[] bytes = new byte[] { (byte) (value.charAt(0) - '0') }; 638 return new ExifAttribute(IFD_FORMAT_BYTE, bytes.length, bytes); 639 } 640 final byte[] ascii = value.getBytes(ASCII); 641 return new ExifAttribute(IFD_FORMAT_BYTE, ascii.length, ascii); 642 } 643 644 public static ExifAttribute createString(String value) { 645 final byte[] ascii = (value + '\0').getBytes(ASCII); 646 return new ExifAttribute(IFD_FORMAT_STRING, ascii.length, ascii); 647 } 648 649 public static ExifAttribute createURational(Rational[] values, ByteOrder byteOrder) { 650 final ByteBuffer buffer = ByteBuffer.wrap( 651 new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_URATIONAL] * values.length]); 652 buffer.order(byteOrder); 653 for (Rational value : values) { 654 buffer.putInt((int) value.numerator); 655 buffer.putInt((int) value.denominator); 656 } 657 return new ExifAttribute(IFD_FORMAT_URATIONAL, values.length, buffer.array()); 658 } 659 660 public static ExifAttribute createURational(Rational value, ByteOrder byteOrder) { 661 return createURational(new Rational[] {value}, byteOrder); 662 } 663 664 public static ExifAttribute createSRational(Rational[] values, ByteOrder byteOrder) { 665 final ByteBuffer buffer = ByteBuffer.wrap( 666 new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SRATIONAL] * values.length]); 667 buffer.order(byteOrder); 668 for (Rational value : values) { 669 buffer.putInt((int) value.numerator); 670 buffer.putInt((int) value.denominator); 671 } 672 return new ExifAttribute(IFD_FORMAT_SRATIONAL, values.length, buffer.array()); 673 } 674 675 public static ExifAttribute createSRational(Rational value, ByteOrder byteOrder) { 676 return createSRational(new Rational[] {value}, byteOrder); 677 } 678 679 public static ExifAttribute createDouble(double[] values, ByteOrder byteOrder) { 680 final ByteBuffer buffer = ByteBuffer.wrap( 681 new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_DOUBLE] * values.length]); 682 buffer.order(byteOrder); 683 for (double value : values) { 684 buffer.putDouble(value); 685 } 686 return new ExifAttribute(IFD_FORMAT_DOUBLE, values.length, buffer.array()); 687 } 688 689 public static ExifAttribute createDouble(double value, ByteOrder byteOrder) { 690 return createDouble(new double[] {value}, byteOrder); 691 } 692 693 @Override 694 public String toString() { 695 return "(" + IFD_FORMAT_NAMES[format] + ", data length:" + bytes.length + ")"; 696 } 697 698 private Object getValue(ByteOrder byteOrder) { 699 try { 700 ByteOrderedDataInputStream inputStream = 701 new ByteOrderedDataInputStream(bytes); 702 inputStream.setByteOrder(byteOrder); 703 switch (format) { 704 case IFD_FORMAT_BYTE: 705 case IFD_FORMAT_SBYTE: { 706 // Exception for GPSAltitudeRef tag 707 if (bytes.length == 1 && bytes[0] >= 0 && bytes[0] <= 1) { 708 return new String(new char[] { (char) (bytes[0] + '0') }); 709 } 710 return new String(bytes, ASCII); 711 } 712 case IFD_FORMAT_UNDEFINED: 713 case IFD_FORMAT_STRING: { 714 int index = 0; 715 if (numberOfComponents >= EXIF_ASCII_PREFIX.length) { 716 boolean same = true; 717 for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) { 718 if (bytes[i] != EXIF_ASCII_PREFIX[i]) { 719 same = false; 720 break; 721 } 722 } 723 if (same) { 724 index = EXIF_ASCII_PREFIX.length; 725 } 726 } 727 728 StringBuilder stringBuilder = new StringBuilder(); 729 while (index < numberOfComponents) { 730 int ch = bytes[index]; 731 if (ch == 0) { 732 break; 733 } 734 if (ch >= 32) { 735 stringBuilder.append((char) ch); 736 } else { 737 stringBuilder.append('?'); 738 } 739 ++index; 740 } 741 return stringBuilder.toString(); 742 } 743 case IFD_FORMAT_USHORT: { 744 final int[] values = new int[numberOfComponents]; 745 for (int i = 0; i < numberOfComponents; ++i) { 746 values[i] = inputStream.readUnsignedShort(); 747 } 748 return values; 749 } 750 case IFD_FORMAT_ULONG: { 751 final long[] values = new long[numberOfComponents]; 752 for (int i = 0; i < numberOfComponents; ++i) { 753 values[i] = inputStream.readUnsignedInt(); 754 } 755 return values; 756 } 757 case IFD_FORMAT_URATIONAL: { 758 final Rational[] values = new Rational[numberOfComponents]; 759 for (int i = 0; i < numberOfComponents; ++i) { 760 final long numerator = inputStream.readUnsignedInt(); 761 final long denominator = inputStream.readUnsignedInt(); 762 values[i] = new Rational(numerator, denominator); 763 } 764 return values; 765 } 766 case IFD_FORMAT_SSHORT: { 767 final int[] values = new int[numberOfComponents]; 768 for (int i = 0; i < numberOfComponents; ++i) { 769 values[i] = inputStream.readShort(); 770 } 771 return values; 772 } 773 case IFD_FORMAT_SLONG: { 774 final int[] values = new int[numberOfComponents]; 775 for (int i = 0; i < numberOfComponents; ++i) { 776 values[i] = inputStream.readInt(); 777 } 778 return values; 779 } 780 case IFD_FORMAT_SRATIONAL: { 781 final Rational[] values = new Rational[numberOfComponents]; 782 for (int i = 0; i < numberOfComponents; ++i) { 783 final long numerator = inputStream.readInt(); 784 final long denominator = inputStream.readInt(); 785 values[i] = new Rational(numerator, denominator); 786 } 787 return values; 788 } 789 case IFD_FORMAT_SINGLE: { 790 final double[] values = new double[numberOfComponents]; 791 for (int i = 0; i < numberOfComponents; ++i) { 792 values[i] = inputStream.readFloat(); 793 } 794 return values; 795 } 796 case IFD_FORMAT_DOUBLE: { 797 final double[] values = new double[numberOfComponents]; 798 for (int i = 0; i < numberOfComponents; ++i) { 799 values[i] = inputStream.readDouble(); 800 } 801 return values; 802 } 803 default: 804 return null; 805 } 806 } catch (IOException e) { 807 Log.w(TAG, "IOException occurred during reading a value", e); 808 return null; 809 } 810 } 811 812 public double getDoubleValue(ByteOrder byteOrder) { 813 Object value = getValue(byteOrder); 814 if (value == null) { 815 throw new NumberFormatException("NULL can't be converted to a double value"); 816 } 817 if (value instanceof String) { 818 return Double.parseDouble((String) value); 819 } 820 if (value instanceof long[]) { 821 long[] array = (long[]) value; 822 if (array.length == 1) { 823 return array[0]; 824 } 825 throw new NumberFormatException("There are more than one component"); 826 } 827 if (value instanceof int[]) { 828 int[] array = (int[]) value; 829 if (array.length == 1) { 830 return array[0]; 831 } 832 throw new NumberFormatException("There are more than one component"); 833 } 834 if (value instanceof double[]) { 835 double[] array = (double[]) value; 836 if (array.length == 1) { 837 return array[0]; 838 } 839 throw new NumberFormatException("There are more than one component"); 840 } 841 if (value instanceof Rational[]) { 842 Rational[] array = (Rational[]) value; 843 if (array.length == 1) { 844 return array[0].calculate(); 845 } 846 throw new NumberFormatException("There are more than one component"); 847 } 848 throw new NumberFormatException("Couldn't find a double value"); 849 } 850 851 public int getIntValue(ByteOrder byteOrder) { 852 Object value = getValue(byteOrder); 853 if (value == null) { 854 throw new NumberFormatException("NULL can't be converted to a integer value"); 855 } 856 if (value instanceof String) { 857 return Integer.parseInt((String) value); 858 } 859 if (value instanceof long[]) { 860 long[] array = (long[]) value; 861 if (array.length == 1) { 862 return (int) array[0]; 863 } 864 throw new NumberFormatException("There are more than one component"); 865 } 866 if (value instanceof int[]) { 867 int[] array = (int[]) value; 868 if (array.length == 1) { 869 return array[0]; 870 } 871 throw new NumberFormatException("There are more than one component"); 872 } 873 throw new NumberFormatException("Couldn't find a integer value"); 874 } 875 876 public String getStringValue(ByteOrder byteOrder) { 877 Object value = getValue(byteOrder); 878 if (value == null) { 879 return null; 880 } 881 if (value instanceof String) { 882 return (String) value; 883 } 884 885 final StringBuilder stringBuilder = new StringBuilder(); 886 if (value instanceof long[]) { 887 long[] array = (long[]) value; 888 for (int i = 0; i < array.length; ++i) { 889 stringBuilder.append(array[i]); 890 if (i + 1 != array.length) { 891 stringBuilder.append(","); 892 } 893 } 894 return stringBuilder.toString(); 895 } 896 if (value instanceof int[]) { 897 int[] array = (int[]) value; 898 for (int i = 0; i < array.length; ++i) { 899 stringBuilder.append(array[i]); 900 if (i + 1 != array.length) { 901 stringBuilder.append(","); 902 } 903 } 904 return stringBuilder.toString(); 905 } 906 if (value instanceof double[]) { 907 double[] array = (double[]) value; 908 for (int i = 0; i < array.length; ++i) { 909 stringBuilder.append(array[i]); 910 if (i + 1 != array.length) { 911 stringBuilder.append(","); 912 } 913 } 914 return stringBuilder.toString(); 915 } 916 if (value instanceof Rational[]) { 917 Rational[] array = (Rational[]) value; 918 for (int i = 0; i < array.length; ++i) { 919 stringBuilder.append(array[i].numerator); 920 stringBuilder.append('/'); 921 stringBuilder.append(array[i].denominator); 922 if (i + 1 != array.length) { 923 stringBuilder.append(","); 924 } 925 } 926 return stringBuilder.toString(); 927 } 928 return null; 929 } 930 931 public int size() { 932 return IFD_FORMAT_BYTES_PER_FORMAT[format] * numberOfComponents; 933 } 934 } 935 936 // A class for indicating EXIF tag. 937 private static class ExifTag { 938 public final int number; 939 public final String name; 940 public final int primaryFormat; 941 public final int secondaryFormat; 942 943 private ExifTag(String name, int number, int format) { 944 this.name = name; 945 this.number = number; 946 this.primaryFormat = format; 947 this.secondaryFormat = -1; 948 } 949 950 private ExifTag(String name, int number, int primaryFormat, int secondaryFormat) { 951 this.name = name; 952 this.number = number; 953 this.primaryFormat = primaryFormat; 954 this.secondaryFormat = secondaryFormat; 955 } 956 } 957 958 // Primary image IFD TIFF tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) 959 private static final ExifTag[] IFD_TIFF_TAGS = new ExifTag[] { 960 // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images. 961 new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG), 962 new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG), 963 new ExifTag(TAG_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 964 new ExifTag(TAG_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 965 new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT), 966 new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT), 967 new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT), 968 new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING), 969 new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING), 970 new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING), 971 new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 972 new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT), 973 new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT), 974 new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 975 new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 976 new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL), 977 new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL), 978 new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT), 979 new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT), 980 new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT), 981 new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING), 982 new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING), 983 new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING), 984 new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL), 985 new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL), 986 // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1. 987 new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), 988 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG), 989 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG), 990 new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL), 991 new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT), 992 new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT), 993 new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL), 994 new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING), 995 new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), 996 new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), 997 // RW2 file tags 998 // See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html) 999 new ExifTag(TAG_RW2_SENSOR_TOP_BORDER, 4, IFD_FORMAT_ULONG), 1000 new ExifTag(TAG_RW2_SENSOR_LEFT_BORDER, 5, IFD_FORMAT_ULONG), 1001 new ExifTag(TAG_RW2_SENSOR_BOTTOM_BORDER, 6, IFD_FORMAT_ULONG), 1002 new ExifTag(TAG_RW2_SENSOR_RIGHT_BORDER, 7, IFD_FORMAT_ULONG), 1003 new ExifTag(TAG_RW2_ISO, 23, IFD_FORMAT_USHORT), 1004 new ExifTag(TAG_RW2_JPG_FROM_RAW, 46, IFD_FORMAT_UNDEFINED) 1005 }; 1006 1007 // Primary image IFD Exif Private tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) 1008 private static final ExifTag[] IFD_EXIF_TAGS = new ExifTag[] { 1009 new ExifTag(TAG_EXPOSURE_TIME, 33434, IFD_FORMAT_URATIONAL), 1010 new ExifTag(TAG_F_NUMBER, 33437, IFD_FORMAT_URATIONAL), 1011 new ExifTag(TAG_EXPOSURE_PROGRAM, 34850, IFD_FORMAT_USHORT), 1012 new ExifTag(TAG_SPECTRAL_SENSITIVITY, 34852, IFD_FORMAT_STRING), 1013 new ExifTag(TAG_ISO_SPEED_RATINGS, 34855, IFD_FORMAT_USHORT), 1014 new ExifTag(TAG_OECF, 34856, IFD_FORMAT_UNDEFINED), 1015 new ExifTag(TAG_EXIF_VERSION, 36864, IFD_FORMAT_STRING), 1016 new ExifTag(TAG_DATETIME_ORIGINAL, 36867, IFD_FORMAT_STRING), 1017 new ExifTag(TAG_DATETIME_DIGITIZED, 36868, IFD_FORMAT_STRING), 1018 new ExifTag(TAG_COMPONENTS_CONFIGURATION, 37121, IFD_FORMAT_UNDEFINED), 1019 new ExifTag(TAG_COMPRESSED_BITS_PER_PIXEL, 37122, IFD_FORMAT_URATIONAL), 1020 new ExifTag(TAG_SHUTTER_SPEED_VALUE, 37377, IFD_FORMAT_SRATIONAL), 1021 new ExifTag(TAG_APERTURE_VALUE, 37378, IFD_FORMAT_URATIONAL), 1022 new ExifTag(TAG_BRIGHTNESS_VALUE, 37379, IFD_FORMAT_SRATIONAL), 1023 new ExifTag(TAG_EXPOSURE_BIAS_VALUE, 37380, IFD_FORMAT_SRATIONAL), 1024 new ExifTag(TAG_MAX_APERTURE_VALUE, 37381, IFD_FORMAT_URATIONAL), 1025 new ExifTag(TAG_SUBJECT_DISTANCE, 37382, IFD_FORMAT_URATIONAL), 1026 new ExifTag(TAG_METERING_MODE, 37383, IFD_FORMAT_USHORT), 1027 new ExifTag(TAG_LIGHT_SOURCE, 37384, IFD_FORMAT_USHORT), 1028 new ExifTag(TAG_FLASH, 37385, IFD_FORMAT_USHORT), 1029 new ExifTag(TAG_FOCAL_LENGTH, 37386, IFD_FORMAT_URATIONAL), 1030 new ExifTag(TAG_SUBJECT_AREA, 37396, IFD_FORMAT_USHORT), 1031 new ExifTag(TAG_MAKER_NOTE, 37500, IFD_FORMAT_UNDEFINED), 1032 new ExifTag(TAG_USER_COMMENT, 37510, IFD_FORMAT_UNDEFINED), 1033 new ExifTag(TAG_SUBSEC_TIME, 37520, IFD_FORMAT_STRING), 1034 new ExifTag(TAG_SUBSEC_TIME_ORIG, 37521, IFD_FORMAT_STRING), 1035 new ExifTag(TAG_SUBSEC_TIME_DIG, 37522, IFD_FORMAT_STRING), 1036 new ExifTag(TAG_FLASHPIX_VERSION, 40960, IFD_FORMAT_UNDEFINED), 1037 new ExifTag(TAG_COLOR_SPACE, 40961, IFD_FORMAT_USHORT), 1038 new ExifTag(TAG_PIXEL_X_DIMENSION, 40962, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 1039 new ExifTag(TAG_PIXEL_Y_DIMENSION, 40963, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 1040 new ExifTag(TAG_RELATED_SOUND_FILE, 40964, IFD_FORMAT_STRING), 1041 new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG), 1042 new ExifTag(TAG_FLASH_ENERGY, 41483, IFD_FORMAT_URATIONAL), 1043 new ExifTag(TAG_SPATIAL_FREQUENCY_RESPONSE, 41484, IFD_FORMAT_UNDEFINED), 1044 new ExifTag(TAG_FOCAL_PLANE_X_RESOLUTION, 41486, IFD_FORMAT_URATIONAL), 1045 new ExifTag(TAG_FOCAL_PLANE_Y_RESOLUTION, 41487, IFD_FORMAT_URATIONAL), 1046 new ExifTag(TAG_FOCAL_PLANE_RESOLUTION_UNIT, 41488, IFD_FORMAT_USHORT), 1047 new ExifTag(TAG_SUBJECT_LOCATION, 41492, IFD_FORMAT_USHORT), 1048 new ExifTag(TAG_EXPOSURE_INDEX, 41493, IFD_FORMAT_URATIONAL), 1049 new ExifTag(TAG_SENSING_METHOD, 41495, IFD_FORMAT_USHORT), 1050 new ExifTag(TAG_FILE_SOURCE, 41728, IFD_FORMAT_UNDEFINED), 1051 new ExifTag(TAG_SCENE_TYPE, 41729, IFD_FORMAT_UNDEFINED), 1052 new ExifTag(TAG_CFA_PATTERN, 41730, IFD_FORMAT_UNDEFINED), 1053 new ExifTag(TAG_CUSTOM_RENDERED, 41985, IFD_FORMAT_USHORT), 1054 new ExifTag(TAG_EXPOSURE_MODE, 41986, IFD_FORMAT_USHORT), 1055 new ExifTag(TAG_WHITE_BALANCE, 41987, IFD_FORMAT_USHORT), 1056 new ExifTag(TAG_DIGITAL_ZOOM_RATIO, 41988, IFD_FORMAT_URATIONAL), 1057 new ExifTag(TAG_FOCAL_LENGTH_IN_35MM_FILM, 41989, IFD_FORMAT_USHORT), 1058 new ExifTag(TAG_SCENE_CAPTURE_TYPE, 41990, IFD_FORMAT_USHORT), 1059 new ExifTag(TAG_GAIN_CONTROL, 41991, IFD_FORMAT_USHORT), 1060 new ExifTag(TAG_CONTRAST, 41992, IFD_FORMAT_USHORT), 1061 new ExifTag(TAG_SATURATION, 41993, IFD_FORMAT_USHORT), 1062 new ExifTag(TAG_SHARPNESS, 41994, IFD_FORMAT_USHORT), 1063 new ExifTag(TAG_DEVICE_SETTING_DESCRIPTION, 41995, IFD_FORMAT_UNDEFINED), 1064 new ExifTag(TAG_SUBJECT_DISTANCE_RANGE, 41996, IFD_FORMAT_USHORT), 1065 new ExifTag(TAG_IMAGE_UNIQUE_ID, 42016, IFD_FORMAT_STRING), 1066 new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE), 1067 new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG) 1068 }; 1069 1070 // Primary image IFD GPS Info tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) 1071 private static final ExifTag[] IFD_GPS_TAGS = new ExifTag[] { 1072 new ExifTag(TAG_GPS_VERSION_ID, 0, IFD_FORMAT_BYTE), 1073 new ExifTag(TAG_GPS_LATITUDE_REF, 1, IFD_FORMAT_STRING), 1074 new ExifTag(TAG_GPS_LATITUDE, 2, IFD_FORMAT_URATIONAL), 1075 new ExifTag(TAG_GPS_LONGITUDE_REF, 3, IFD_FORMAT_STRING), 1076 new ExifTag(TAG_GPS_LONGITUDE, 4, IFD_FORMAT_URATIONAL), 1077 new ExifTag(TAG_GPS_ALTITUDE_REF, 5, IFD_FORMAT_BYTE), 1078 new ExifTag(TAG_GPS_ALTITUDE, 6, IFD_FORMAT_URATIONAL), 1079 new ExifTag(TAG_GPS_TIMESTAMP, 7, IFD_FORMAT_URATIONAL), 1080 new ExifTag(TAG_GPS_SATELLITES, 8, IFD_FORMAT_STRING), 1081 new ExifTag(TAG_GPS_STATUS, 9, IFD_FORMAT_STRING), 1082 new ExifTag(TAG_GPS_MEASURE_MODE, 10, IFD_FORMAT_STRING), 1083 new ExifTag(TAG_GPS_DOP, 11, IFD_FORMAT_URATIONAL), 1084 new ExifTag(TAG_GPS_SPEED_REF, 12, IFD_FORMAT_STRING), 1085 new ExifTag(TAG_GPS_SPEED, 13, IFD_FORMAT_URATIONAL), 1086 new ExifTag(TAG_GPS_TRACK_REF, 14, IFD_FORMAT_STRING), 1087 new ExifTag(TAG_GPS_TRACK, 15, IFD_FORMAT_URATIONAL), 1088 new ExifTag(TAG_GPS_IMG_DIRECTION_REF, 16, IFD_FORMAT_STRING), 1089 new ExifTag(TAG_GPS_IMG_DIRECTION, 17, IFD_FORMAT_URATIONAL), 1090 new ExifTag(TAG_GPS_MAP_DATUM, 18, IFD_FORMAT_STRING), 1091 new ExifTag(TAG_GPS_DEST_LATITUDE_REF, 19, IFD_FORMAT_STRING), 1092 new ExifTag(TAG_GPS_DEST_LATITUDE, 20, IFD_FORMAT_URATIONAL), 1093 new ExifTag(TAG_GPS_DEST_LONGITUDE_REF, 21, IFD_FORMAT_STRING), 1094 new ExifTag(TAG_GPS_DEST_LONGITUDE, 22, IFD_FORMAT_URATIONAL), 1095 new ExifTag(TAG_GPS_DEST_BEARING_REF, 23, IFD_FORMAT_STRING), 1096 new ExifTag(TAG_GPS_DEST_BEARING, 24, IFD_FORMAT_URATIONAL), 1097 new ExifTag(TAG_GPS_DEST_DISTANCE_REF, 25, IFD_FORMAT_STRING), 1098 new ExifTag(TAG_GPS_DEST_DISTANCE, 26, IFD_FORMAT_URATIONAL), 1099 new ExifTag(TAG_GPS_PROCESSING_METHOD, 27, IFD_FORMAT_UNDEFINED), 1100 new ExifTag(TAG_GPS_AREA_INFORMATION, 28, IFD_FORMAT_UNDEFINED), 1101 new ExifTag(TAG_GPS_DATESTAMP, 29, IFD_FORMAT_STRING), 1102 new ExifTag(TAG_GPS_DIFFERENTIAL, 30, IFD_FORMAT_USHORT) 1103 }; 1104 // Primary image IFD Interoperability tag (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) 1105 private static final ExifTag[] IFD_INTEROPERABILITY_TAGS = new ExifTag[] { 1106 new ExifTag(TAG_INTEROPERABILITY_INDEX, 1, IFD_FORMAT_STRING) 1107 }; 1108 // IFD Thumbnail tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) 1109 private static final ExifTag[] IFD_THUMBNAIL_TAGS = new ExifTag[] { 1110 // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images. 1111 new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG), 1112 new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG), 1113 new ExifTag(TAG_THUMBNAIL_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 1114 new ExifTag(TAG_THUMBNAIL_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 1115 new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT), 1116 new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT), 1117 new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT), 1118 new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING), 1119 new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING), 1120 new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING), 1121 new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 1122 new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT), 1123 new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT), 1124 new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 1125 new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), 1126 new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL), 1127 new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL), 1128 new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT), 1129 new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT), 1130 new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT), 1131 new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING), 1132 new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING), 1133 new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING), 1134 new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL), 1135 new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL), 1136 // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1. 1137 new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), 1138 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG), 1139 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG), 1140 new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL), 1141 new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT), 1142 new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT), 1143 new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL), 1144 new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING), 1145 new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), 1146 new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), 1147 new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE), 1148 new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG) 1149 }; 1150 1151 // RAF file tag (See piex.cc line 372) 1152 private static final ExifTag TAG_RAF_IMAGE_SIZE = 1153 new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT); 1154 1155 // ORF file tags (See http://www.exiv2.org/tags-olympus.html) 1156 private static final ExifTag[] ORF_MAKER_NOTE_TAGS = new ExifTag[] { 1157 new ExifTag(TAG_ORF_THUMBNAIL_IMAGE, 256, IFD_FORMAT_UNDEFINED), 1158 new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_ULONG), 1159 new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_ULONG) 1160 }; 1161 private static final ExifTag[] ORF_CAMERA_SETTINGS_TAGS = new ExifTag[] { 1162 new ExifTag(TAG_ORF_PREVIEW_IMAGE_START, 257, IFD_FORMAT_ULONG), 1163 new ExifTag(TAG_ORF_PREVIEW_IMAGE_LENGTH, 258, IFD_FORMAT_ULONG) 1164 }; 1165 private static final ExifTag[] ORF_IMAGE_PROCESSING_TAGS = new ExifTag[] { 1166 new ExifTag(TAG_ORF_ASPECT_FRAME, 4371, IFD_FORMAT_USHORT) 1167 }; 1168 // PEF file tag (See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Pentax.html) 1169 private static final ExifTag[] PEF_TAGS = new ExifTag[] { 1170 new ExifTag(TAG_COLOR_SPACE, 55, IFD_FORMAT_USHORT) 1171 }; 1172 1173 // See JEITA CP-3451C Section 4.6.3: Exif-specific IFD. 1174 // The following values are used for indicating pointers to the other Image File Directories. 1175 1176 // Indices of Exif Ifd tag groups 1177 /** @hide */ 1178 @Retention(RetentionPolicy.SOURCE) 1179 @IntDef({IFD_TYPE_PRIMARY, IFD_TYPE_EXIF, IFD_TYPE_GPS, IFD_TYPE_INTEROPERABILITY, 1180 IFD_TYPE_THUMBNAIL, IFD_TYPE_PREVIEW, IFD_TYPE_ORF_MAKER_NOTE, 1181 IFD_TYPE_ORF_CAMERA_SETTINGS, IFD_TYPE_ORF_IMAGE_PROCESSING, IFD_TYPE_PEF}) 1182 public @interface IfdType {} 1183 1184 private static final int IFD_TYPE_PRIMARY = 0; 1185 private static final int IFD_TYPE_EXIF = 1; 1186 private static final int IFD_TYPE_GPS = 2; 1187 private static final int IFD_TYPE_INTEROPERABILITY = 3; 1188 private static final int IFD_TYPE_THUMBNAIL = 4; 1189 private static final int IFD_TYPE_PREVIEW = 5; 1190 private static final int IFD_TYPE_ORF_MAKER_NOTE = 6; 1191 private static final int IFD_TYPE_ORF_CAMERA_SETTINGS = 7; 1192 private static final int IFD_TYPE_ORF_IMAGE_PROCESSING = 8; 1193 private static final int IFD_TYPE_PEF = 9; 1194 1195 // List of Exif tag groups 1196 private static final ExifTag[][] EXIF_TAGS = new ExifTag[][] { 1197 IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS, 1198 IFD_THUMBNAIL_TAGS, IFD_TIFF_TAGS, ORF_MAKER_NOTE_TAGS, ORF_CAMERA_SETTINGS_TAGS, 1199 ORF_IMAGE_PROCESSING_TAGS, PEF_TAGS 1200 }; 1201 // List of tags for pointing to the other image file directory offset. 1202 private static final ExifTag[] EXIF_POINTER_TAGS = new ExifTag[] { 1203 new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), 1204 new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), 1205 new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), 1206 new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG), 1207 new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_BYTE), 1208 new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_BYTE) 1209 }; 1210 1211 // Tags for indicating the thumbnail offset and length 1212 private static final ExifTag JPEG_INTERCHANGE_FORMAT_TAG = 1213 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG); 1214 private static final ExifTag JPEG_INTERCHANGE_FORMAT_LENGTH_TAG = 1215 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG); 1216 1217 // Mappings from tag number to tag name and each item represents one IFD tag group. 1218 private static final HashMap[] sExifTagMapsForReading = new HashMap[EXIF_TAGS.length]; 1219 // Mappings from tag name to tag number and each item represents one IFD tag group. 1220 private static final HashMap[] sExifTagMapsForWriting = new HashMap[EXIF_TAGS.length]; 1221 private static final HashSet<String> sTagSetForCompatibility = new HashSet<>(Arrays.asList( 1222 TAG_F_NUMBER, TAG_DIGITAL_ZOOM_RATIO, TAG_EXPOSURE_TIME, TAG_SUBJECT_DISTANCE, 1223 TAG_GPS_TIMESTAMP)); 1224 // Mappings from tag number to IFD type for pointer tags. 1225 private static final HashMap sExifPointerTagMap = new HashMap(); 1226 1227 // See JPEG File Interchange Format Version 1.02. 1228 // The following values are defined for handling JPEG streams. In this implementation, we are 1229 // not only getting information from EXIF but also from some JPEG special segments such as 1230 // MARKER_COM for user comment and MARKER_SOFx for image width and height. 1231 1232 private static final Charset ASCII = Charset.forName("US-ASCII"); 1233 // Identifier for EXIF APP1 segment in JPEG 1234 private static final byte[] IDENTIFIER_EXIF_APP1 = "Exif\0\0".getBytes(ASCII); 1235 // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with 1236 // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start 1237 // of frame(baseline DCT) and the image size info exists in its beginning part. 1238 private static final byte MARKER = (byte) 0xff; 1239 private static final byte MARKER_SOI = (byte) 0xd8; 1240 private static final byte MARKER_SOF0 = (byte) 0xc0; 1241 private static final byte MARKER_SOF1 = (byte) 0xc1; 1242 private static final byte MARKER_SOF2 = (byte) 0xc2; 1243 private static final byte MARKER_SOF3 = (byte) 0xc3; 1244 private static final byte MARKER_SOF5 = (byte) 0xc5; 1245 private static final byte MARKER_SOF6 = (byte) 0xc6; 1246 private static final byte MARKER_SOF7 = (byte) 0xc7; 1247 private static final byte MARKER_SOF9 = (byte) 0xc9; 1248 private static final byte MARKER_SOF10 = (byte) 0xca; 1249 private static final byte MARKER_SOF11 = (byte) 0xcb; 1250 private static final byte MARKER_SOF13 = (byte) 0xcd; 1251 private static final byte MARKER_SOF14 = (byte) 0xce; 1252 private static final byte MARKER_SOF15 = (byte) 0xcf; 1253 private static final byte MARKER_SOS = (byte) 0xda; 1254 private static final byte MARKER_APP1 = (byte) 0xe1; 1255 private static final byte MARKER_COM = (byte) 0xfe; 1256 private static final byte MARKER_EOI = (byte) 0xd9; 1257 1258 // Supported Image File Types 1259 private static final int IMAGE_TYPE_UNKNOWN = 0; 1260 private static final int IMAGE_TYPE_ARW = 1; 1261 private static final int IMAGE_TYPE_CR2 = 2; 1262 private static final int IMAGE_TYPE_DNG = 3; 1263 private static final int IMAGE_TYPE_JPEG = 4; 1264 private static final int IMAGE_TYPE_NEF = 5; 1265 private static final int IMAGE_TYPE_NRW = 6; 1266 private static final int IMAGE_TYPE_ORF = 7; 1267 private static final int IMAGE_TYPE_PEF = 8; 1268 private static final int IMAGE_TYPE_RAF = 9; 1269 private static final int IMAGE_TYPE_RW2 = 10; 1270 private static final int IMAGE_TYPE_SRW = 11; 1271 private static final int IMAGE_TYPE_HEIF = 12; 1272 1273 static { 1274 sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); 1275 sFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); 1276 1277 // Build up the hash tables to look up Exif tags for reading Exif tags. 1278 for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { 1279 sExifTagMapsForReading[ifdType] = new HashMap(); 1280 sExifTagMapsForWriting[ifdType] = new HashMap(); 1281 for (ExifTag tag : EXIF_TAGS[ifdType]) { 1282 sExifTagMapsForReading[ifdType].put(tag.number, tag); 1283 sExifTagMapsForWriting[ifdType].put(tag.name, tag); 1284 } 1285 } 1286 1287 // Build up the hash table to look up Exif pointer tags. 1288 sExifPointerTagMap.put(EXIF_POINTER_TAGS[0].number, IFD_TYPE_PREVIEW); // 330 1289 sExifPointerTagMap.put(EXIF_POINTER_TAGS[1].number, IFD_TYPE_EXIF); // 34665 1290 sExifPointerTagMap.put(EXIF_POINTER_TAGS[2].number, IFD_TYPE_GPS); // 34853 1291 sExifPointerTagMap.put(EXIF_POINTER_TAGS[3].number, IFD_TYPE_INTEROPERABILITY); // 40965 1292 sExifPointerTagMap.put(EXIF_POINTER_TAGS[4].number, IFD_TYPE_ORF_CAMERA_SETTINGS); // 8224 1293 sExifPointerTagMap.put(EXIF_POINTER_TAGS[5].number, IFD_TYPE_ORF_IMAGE_PROCESSING); // 8256 1294 } 1295 1296 private final String mFilename; 1297 private final FileDescriptor mSeekableFileDescriptor; 1298 private final AssetManager.AssetInputStream mAssetInputStream; 1299 private final boolean mIsInputStream; 1300 private int mMimeType; 1301 private final HashMap[] mAttributes = new HashMap[EXIF_TAGS.length]; 1302 private ByteOrder mExifByteOrder = ByteOrder.BIG_ENDIAN; 1303 private boolean mHasThumbnail; 1304 // The following values used for indicating a thumbnail position. 1305 private int mThumbnailOffset; 1306 private int mThumbnailLength; 1307 private byte[] mThumbnailBytes; 1308 private int mThumbnailCompression; 1309 private int mExifOffset; 1310 private int mOrfMakerNoteOffset; 1311 private int mOrfThumbnailOffset; 1312 private int mOrfThumbnailLength; 1313 private int mRw2JpgFromRawOffset; 1314 private boolean mIsSupportedFile; 1315 1316 // Pattern to check non zero timestamp 1317 private static final Pattern sNonZeroTimePattern = Pattern.compile(".*[1-9].*"); 1318 // Pattern to check gps timestamp 1319 private static final Pattern sGpsTimestampPattern = 1320 Pattern.compile("^([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$"); 1321 1322 /** 1323 * Reads Exif tags from the specified image file. 1324 */ 1325 public ExifInterface(String filename) throws IOException { 1326 if (filename == null) { 1327 throw new IllegalArgumentException("filename cannot be null"); 1328 } 1329 FileInputStream in = null; 1330 mAssetInputStream = null; 1331 mFilename = filename; 1332 mIsInputStream = false; 1333 try { 1334 in = new FileInputStream(filename); 1335 if (isSeekableFD(in.getFD())) { 1336 mSeekableFileDescriptor = in.getFD(); 1337 } else { 1338 mSeekableFileDescriptor = null; 1339 } 1340 loadAttributes(in); 1341 } finally { 1342 IoUtils.closeQuietly(in); 1343 } 1344 } 1345 1346 /** 1347 * Reads Exif tags from the specified image file descriptor. Attribute mutation is supported 1348 * for writable and seekable file descriptors only. This constructor will not rewind the offset 1349 * of the given file descriptor. Developers should close the file descriptor after use. 1350 */ 1351 public ExifInterface(FileDescriptor fileDescriptor) throws IOException { 1352 if (fileDescriptor == null) { 1353 throw new IllegalArgumentException("fileDescriptor cannot be null"); 1354 } 1355 mAssetInputStream = null; 1356 mFilename = null; 1357 if (isSeekableFD(fileDescriptor)) { 1358 mSeekableFileDescriptor = fileDescriptor; 1359 // Keep the original file descriptor in order to save attributes when it's seekable. 1360 // Otherwise, just close the given file descriptor after reading it because the save 1361 // feature won't be working. 1362 try { 1363 fileDescriptor = Os.dup(fileDescriptor); 1364 } catch (ErrnoException e) { 1365 throw e.rethrowAsIOException(); 1366 } 1367 } else { 1368 mSeekableFileDescriptor = null; 1369 } 1370 mIsInputStream = false; 1371 FileInputStream in = null; 1372 try { 1373 in = new FileInputStream(fileDescriptor); 1374 loadAttributes(in); 1375 } finally { 1376 IoUtils.closeQuietly(in); 1377 } 1378 } 1379 1380 /** 1381 * Reads Exif tags from the specified image input stream. Attribute mutation is not supported 1382 * for input streams. The given input stream will proceed its current position. Developers 1383 * should close the input stream after use. 1384 */ 1385 public ExifInterface(InputStream inputStream) throws IOException { 1386 if (inputStream == null) { 1387 throw new IllegalArgumentException("inputStream cannot be null"); 1388 } 1389 mFilename = null; 1390 if (inputStream instanceof AssetManager.AssetInputStream) { 1391 mAssetInputStream = (AssetManager.AssetInputStream) inputStream; 1392 mSeekableFileDescriptor = null; 1393 } else if (inputStream instanceof FileInputStream 1394 && isSeekableFD(((FileInputStream) inputStream).getFD())) { 1395 mAssetInputStream = null; 1396 mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD(); 1397 } else { 1398 mAssetInputStream = null; 1399 mSeekableFileDescriptor = null; 1400 } 1401 mIsInputStream = true; 1402 loadAttributes(inputStream); 1403 } 1404 1405 /** 1406 * Returns the EXIF attribute of the specified tag or {@code null} if there is no such tag in 1407 * the image file. 1408 * 1409 * @param tag the name of the tag. 1410 */ 1411 private ExifAttribute getExifAttribute(String tag) { 1412 // Retrieves all tag groups. The value from primary image tag group has a higher priority 1413 // than the value from the thumbnail tag group if there are more than one candidates. 1414 for (int i = 0; i < EXIF_TAGS.length; ++i) { 1415 Object value = mAttributes[i].get(tag); 1416 if (value != null) { 1417 return (ExifAttribute) value; 1418 } 1419 } 1420 return null; 1421 } 1422 1423 /** 1424 * Returns the value of the specified tag or {@code null} if there 1425 * is no such tag in the image file. 1426 * 1427 * @param tag the name of the tag. 1428 */ 1429 public String getAttribute(String tag) { 1430 ExifAttribute attribute = getExifAttribute(tag); 1431 if (attribute != null) { 1432 if (!sTagSetForCompatibility.contains(tag)) { 1433 return attribute.getStringValue(mExifByteOrder); 1434 } 1435 if (tag.equals(TAG_GPS_TIMESTAMP)) { 1436 // Convert the rational values to the custom formats for backwards compatibility. 1437 if (attribute.format != IFD_FORMAT_URATIONAL 1438 && attribute.format != IFD_FORMAT_SRATIONAL) { 1439 return null; 1440 } 1441 Rational[] array = (Rational[]) attribute.getValue(mExifByteOrder); 1442 if (array.length != 3) { 1443 return null; 1444 } 1445 return String.format("%02d:%02d:%02d", 1446 (int) ((float) array[0].numerator / array[0].denominator), 1447 (int) ((float) array[1].numerator / array[1].denominator), 1448 (int) ((float) array[2].numerator / array[2].denominator)); 1449 } 1450 try { 1451 return Double.toString(attribute.getDoubleValue(mExifByteOrder)); 1452 } catch (NumberFormatException e) { 1453 return null; 1454 } 1455 } 1456 return null; 1457 } 1458 1459 /** 1460 * Returns the integer value of the specified tag. If there is no such tag 1461 * in the image file or the value cannot be parsed as integer, return 1462 * <var>defaultValue</var>. 1463 * 1464 * @param tag the name of the tag. 1465 * @param defaultValue the value to return if the tag is not available. 1466 */ 1467 public int getAttributeInt(String tag, int defaultValue) { 1468 ExifAttribute exifAttribute = getExifAttribute(tag); 1469 if (exifAttribute == null) { 1470 return defaultValue; 1471 } 1472 1473 try { 1474 return exifAttribute.getIntValue(mExifByteOrder); 1475 } catch (NumberFormatException e) { 1476 return defaultValue; 1477 } 1478 } 1479 1480 /** 1481 * Returns the double value of the tag that is specified as rational or contains a 1482 * double-formatted value. If there is no such tag in the image file or the value cannot be 1483 * parsed as double, return <var>defaultValue</var>. 1484 * 1485 * @param tag the name of the tag. 1486 * @param defaultValue the value to return if the tag is not available. 1487 */ 1488 public double getAttributeDouble(String tag, double defaultValue) { 1489 ExifAttribute exifAttribute = getExifAttribute(tag); 1490 if (exifAttribute == null) { 1491 return defaultValue; 1492 } 1493 1494 try { 1495 return exifAttribute.getDoubleValue(mExifByteOrder); 1496 } catch (NumberFormatException e) { 1497 return defaultValue; 1498 } 1499 } 1500 1501 /** 1502 * Set the value of the specified tag. 1503 * 1504 * @param tag the name of the tag. 1505 * @param value the value of the tag. 1506 */ 1507 public void setAttribute(String tag, String value) { 1508 // Convert the given value to rational values for backwards compatibility. 1509 if (value != null && sTagSetForCompatibility.contains(tag)) { 1510 if (tag.equals(TAG_GPS_TIMESTAMP)) { 1511 Matcher m = sGpsTimestampPattern.matcher(value); 1512 if (!m.find()) { 1513 Log.w(TAG, "Invalid value for " + tag + " : " + value); 1514 return; 1515 } 1516 value = Integer.parseInt(m.group(1)) + "/1," + Integer.parseInt(m.group(2)) + "/1," 1517 + Integer.parseInt(m.group(3)) + "/1"; 1518 } else { 1519 try { 1520 double doubleValue = Double.parseDouble(value); 1521 value = (long) (doubleValue * 10000L) + "/10000"; 1522 } catch (NumberFormatException e) { 1523 Log.w(TAG, "Invalid value for " + tag + " : " + value); 1524 return; 1525 } 1526 } 1527 } 1528 1529 for (int i = 0 ; i < EXIF_TAGS.length; ++i) { 1530 if (i == IFD_TYPE_THUMBNAIL && !mHasThumbnail) { 1531 continue; 1532 } 1533 final Object obj = sExifTagMapsForWriting[i].get(tag); 1534 if (obj != null) { 1535 if (value == null) { 1536 mAttributes[i].remove(tag); 1537 continue; 1538 } 1539 final ExifTag exifTag = (ExifTag) obj; 1540 Pair<Integer, Integer> guess = guessDataFormat(value); 1541 int dataFormat; 1542 if (exifTag.primaryFormat == guess.first || exifTag.primaryFormat == guess.second) { 1543 dataFormat = exifTag.primaryFormat; 1544 } else if (exifTag.secondaryFormat != -1 && (exifTag.secondaryFormat == guess.first 1545 || exifTag.secondaryFormat == guess.second)) { 1546 dataFormat = exifTag.secondaryFormat; 1547 } else if (exifTag.primaryFormat == IFD_FORMAT_BYTE 1548 || exifTag.primaryFormat == IFD_FORMAT_UNDEFINED 1549 || exifTag.primaryFormat == IFD_FORMAT_STRING) { 1550 dataFormat = exifTag.primaryFormat; 1551 } else { 1552 Log.w(TAG, "Given tag (" + tag + ") value didn't match with one of expected " 1553 + "formats: " + IFD_FORMAT_NAMES[exifTag.primaryFormat] 1554 + (exifTag.secondaryFormat == -1 ? "" : ", " 1555 + IFD_FORMAT_NAMES[exifTag.secondaryFormat]) + " (guess: " 1556 + IFD_FORMAT_NAMES[guess.first] + (guess.second == -1 ? "" : ", " 1557 + IFD_FORMAT_NAMES[guess.second]) + ")"); 1558 continue; 1559 } 1560 switch (dataFormat) { 1561 case IFD_FORMAT_BYTE: { 1562 mAttributes[i].put(tag, ExifAttribute.createByte(value)); 1563 break; 1564 } 1565 case IFD_FORMAT_UNDEFINED: 1566 case IFD_FORMAT_STRING: { 1567 mAttributes[i].put(tag, ExifAttribute.createString(value)); 1568 break; 1569 } 1570 case IFD_FORMAT_USHORT: { 1571 final String[] values = value.split(","); 1572 final int[] intArray = new int[values.length]; 1573 for (int j = 0; j < values.length; ++j) { 1574 intArray[j] = Integer.parseInt(values[j]); 1575 } 1576 mAttributes[i].put(tag, 1577 ExifAttribute.createUShort(intArray, mExifByteOrder)); 1578 break; 1579 } 1580 case IFD_FORMAT_SLONG: { 1581 final String[] values = value.split(","); 1582 final int[] intArray = new int[values.length]; 1583 for (int j = 0; j < values.length; ++j) { 1584 intArray[j] = Integer.parseInt(values[j]); 1585 } 1586 mAttributes[i].put(tag, 1587 ExifAttribute.createSLong(intArray, mExifByteOrder)); 1588 break; 1589 } 1590 case IFD_FORMAT_ULONG: { 1591 final String[] values = value.split(","); 1592 final long[] longArray = new long[values.length]; 1593 for (int j = 0; j < values.length; ++j) { 1594 longArray[j] = Long.parseLong(values[j]); 1595 } 1596 mAttributes[i].put(tag, 1597 ExifAttribute.createULong(longArray, mExifByteOrder)); 1598 break; 1599 } 1600 case IFD_FORMAT_URATIONAL: { 1601 final String[] values = value.split(","); 1602 final Rational[] rationalArray = new Rational[values.length]; 1603 for (int j = 0; j < values.length; ++j) { 1604 final String[] numbers = values[j].split("/"); 1605 rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]), 1606 (long) Double.parseDouble(numbers[1])); 1607 } 1608 mAttributes[i].put(tag, 1609 ExifAttribute.createURational(rationalArray, mExifByteOrder)); 1610 break; 1611 } 1612 case IFD_FORMAT_SRATIONAL: { 1613 final String[] values = value.split(","); 1614 final Rational[] rationalArray = new Rational[values.length]; 1615 for (int j = 0; j < values.length; ++j) { 1616 final String[] numbers = values[j].split("/"); 1617 rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]), 1618 (long) Double.parseDouble(numbers[1])); 1619 } 1620 mAttributes[i].put(tag, 1621 ExifAttribute.createSRational(rationalArray, mExifByteOrder)); 1622 break; 1623 } 1624 case IFD_FORMAT_DOUBLE: { 1625 final String[] values = value.split(","); 1626 final double[] doubleArray = new double[values.length]; 1627 for (int j = 0; j < values.length; ++j) { 1628 doubleArray[j] = Double.parseDouble(values[j]); 1629 } 1630 mAttributes[i].put(tag, 1631 ExifAttribute.createDouble(doubleArray, mExifByteOrder)); 1632 break; 1633 } 1634 default: 1635 Log.w(TAG, "Data format isn't one of expected formats: " + dataFormat); 1636 continue; 1637 } 1638 } 1639 } 1640 } 1641 1642 /** 1643 * Update the values of the tags in the tag groups if any value for the tag already was stored. 1644 * 1645 * @param tag the name of the tag. 1646 * @param value the value of the tag in a form of {@link ExifAttribute}. 1647 * @return Returns {@code true} if updating is placed. 1648 */ 1649 private boolean updateAttribute(String tag, ExifAttribute value) { 1650 boolean updated = false; 1651 for (int i = 0 ; i < EXIF_TAGS.length; ++i) { 1652 if (mAttributes[i].containsKey(tag)) { 1653 mAttributes[i].put(tag, value); 1654 updated = true; 1655 } 1656 } 1657 return updated; 1658 } 1659 1660 /** 1661 * Remove any values of the specified tag. 1662 * 1663 * @param tag the name of the tag. 1664 */ 1665 private void removeAttribute(String tag) { 1666 for (int i = 0 ; i < EXIF_TAGS.length; ++i) { 1667 mAttributes[i].remove(tag); 1668 } 1669 } 1670 1671 /** 1672 * This function decides which parser to read the image data according to the given input stream 1673 * type and the content of the input stream. In each case, it reads the first three bytes to 1674 * determine whether the image data format is JPEG or not. 1675 */ 1676 private void loadAttributes(@NonNull InputStream in) throws IOException { 1677 try { 1678 // Initialize mAttributes. 1679 for (int i = 0; i < EXIF_TAGS.length; ++i) { 1680 mAttributes[i] = new HashMap(); 1681 } 1682 1683 // Check file type 1684 in = new BufferedInputStream(in, SIGNATURE_CHECK_SIZE); 1685 mMimeType = getMimeType((BufferedInputStream) in); 1686 1687 // Create byte-ordered input stream 1688 ByteOrderedDataInputStream inputStream = new ByteOrderedDataInputStream(in); 1689 1690 switch (mMimeType) { 1691 case IMAGE_TYPE_JPEG: { 1692 getJpegAttributes(inputStream, 0, IFD_TYPE_PRIMARY); // 0 is offset 1693 break; 1694 } 1695 case IMAGE_TYPE_RAF: { 1696 getRafAttributes(inputStream); 1697 break; 1698 } 1699 case IMAGE_TYPE_HEIF: { 1700 getHeifAttributes(inputStream); 1701 break; 1702 } 1703 case IMAGE_TYPE_ORF: { 1704 getOrfAttributes(inputStream); 1705 break; 1706 } 1707 case IMAGE_TYPE_RW2: { 1708 getRw2Attributes(inputStream); 1709 break; 1710 } 1711 case IMAGE_TYPE_ARW: 1712 case IMAGE_TYPE_CR2: 1713 case IMAGE_TYPE_DNG: 1714 case IMAGE_TYPE_NEF: 1715 case IMAGE_TYPE_NRW: 1716 case IMAGE_TYPE_PEF: 1717 case IMAGE_TYPE_SRW: 1718 case IMAGE_TYPE_UNKNOWN: { 1719 getRawAttributes(inputStream); 1720 break; 1721 } 1722 default: { 1723 break; 1724 } 1725 } 1726 // Set thumbnail image offset and length 1727 setThumbnailData(inputStream); 1728 mIsSupportedFile = true; 1729 } catch (IOException e) { 1730 // Ignore exceptions in order to keep the compatibility with the old versions of 1731 // ExifInterface. 1732 mIsSupportedFile = false; 1733 if (DEBUG) { 1734 Log.w(TAG, "Invalid image: ExifInterface got an unsupported image format file" 1735 + "(ExifInterface supports JPEG and some RAW image formats only) " 1736 + "or a corrupted JPEG file to ExifInterface.", e); 1737 } 1738 } finally { 1739 addDefaultValuesForCompatibility(); 1740 1741 if (DEBUG) { 1742 printAttributes(); 1743 } 1744 } 1745 } 1746 1747 private static boolean isSeekableFD(FileDescriptor fd) throws IOException { 1748 try { 1749 Os.lseek(fd, 0, OsConstants.SEEK_CUR); 1750 return true; 1751 } catch (ErrnoException e) { 1752 return false; 1753 } 1754 } 1755 1756 // Prints out attributes for debugging. 1757 private void printAttributes() { 1758 for (int i = 0; i < mAttributes.length; ++i) { 1759 Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size()); 1760 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) { 1761 final ExifAttribute tagValue = (ExifAttribute) entry.getValue(); 1762 Log.d(TAG, "tagName: " + entry.getKey() + ", tagType: " + tagValue.toString() 1763 + ", tagValue: '" + tagValue.getStringValue(mExifByteOrder) + "'"); 1764 } 1765 } 1766 } 1767 1768 /** 1769 * Save the tag data into the original image file. This is expensive because it involves 1770 * copying all the data from one file to another and deleting the old file and renaming the 1771 * other. It's best to use {@link #setAttribute(String,String)} to set all attributes to write 1772 * and make a single call rather than multiple calls for each attribute. 1773 * <p> 1774 * This method is only supported for JPEG files. 1775 * </p> 1776 */ 1777 public void saveAttributes() throws IOException { 1778 if (!mIsSupportedFile || mMimeType != IMAGE_TYPE_JPEG) { 1779 throw new IOException("ExifInterface only supports saving attributes on JPEG formats."); 1780 } 1781 if (mIsInputStream || (mSeekableFileDescriptor == null && mFilename == null)) { 1782 throw new IOException( 1783 "ExifInterface does not support saving attributes for the current input."); 1784 } 1785 1786 // Keep the thumbnail in memory 1787 mThumbnailBytes = getThumbnail(); 1788 1789 FileInputStream in = null; 1790 FileOutputStream out = null; 1791 File tempFile = null; 1792 try { 1793 // Move the original file to temporary file. 1794 if (mFilename != null) { 1795 tempFile = new File(mFilename + ".tmp"); 1796 File originalFile = new File(mFilename); 1797 if (!originalFile.renameTo(tempFile)) { 1798 throw new IOException("Could'nt rename to " + tempFile.getAbsolutePath()); 1799 } 1800 } else if (mSeekableFileDescriptor != null) { 1801 tempFile = File.createTempFile("temp", "jpg"); 1802 Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET); 1803 in = new FileInputStream(mSeekableFileDescriptor); 1804 out = new FileOutputStream(tempFile); 1805 Streams.copy(in, out); 1806 } 1807 } catch (ErrnoException e) { 1808 throw e.rethrowAsIOException(); 1809 } finally { 1810 IoUtils.closeQuietly(in); 1811 IoUtils.closeQuietly(out); 1812 } 1813 1814 in = null; 1815 out = null; 1816 try { 1817 // Save the new file. 1818 in = new FileInputStream(tempFile); 1819 if (mFilename != null) { 1820 out = new FileOutputStream(mFilename); 1821 } else if (mSeekableFileDescriptor != null) { 1822 Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET); 1823 out = new FileOutputStream(mSeekableFileDescriptor); 1824 } 1825 saveJpegAttributes(in, out); 1826 } catch (ErrnoException e) { 1827 throw e.rethrowAsIOException(); 1828 } finally { 1829 IoUtils.closeQuietly(in); 1830 IoUtils.closeQuietly(out); 1831 tempFile.delete(); 1832 } 1833 1834 // Discard the thumbnail in memory 1835 mThumbnailBytes = null; 1836 } 1837 1838 /** 1839 * Returns true if the image file has a thumbnail. 1840 */ 1841 public boolean hasThumbnail() { 1842 return mHasThumbnail; 1843 } 1844 1845 /** 1846 * Returns the JPEG compressed thumbnail inside the image file, or {@code null} if there is no 1847 * JPEG compressed thumbnail. 1848 * The returned data can be decoded using 1849 * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)} 1850 */ 1851 public byte[] getThumbnail() { 1852 if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { 1853 return getThumbnailBytes(); 1854 } 1855 return null; 1856 } 1857 1858 /** 1859 * Returns the thumbnail bytes inside the image file, regardless of the compression type of the 1860 * thumbnail image. 1861 */ 1862 public byte[] getThumbnailBytes() { 1863 if (!mHasThumbnail) { 1864 return null; 1865 } 1866 if (mThumbnailBytes != null) { 1867 return mThumbnailBytes; 1868 } 1869 1870 // Read the thumbnail. 1871 InputStream in = null; 1872 try { 1873 if (mAssetInputStream != null) { 1874 in = mAssetInputStream; 1875 if (in.markSupported()) { 1876 in.reset(); 1877 } else { 1878 Log.d(TAG, "Cannot read thumbnail from inputstream without mark/reset support"); 1879 return null; 1880 } 1881 } else if (mFilename != null) { 1882 in = new FileInputStream(mFilename); 1883 } else if (mSeekableFileDescriptor != null) { 1884 FileDescriptor fileDescriptor = Os.dup(mSeekableFileDescriptor); 1885 Os.lseek(fileDescriptor, 0, OsConstants.SEEK_SET); 1886 in = new FileInputStream(fileDescriptor); 1887 } 1888 if (in == null) { 1889 // Should not be reached this. 1890 throw new FileNotFoundException(); 1891 } 1892 if (in.skip(mThumbnailOffset) != mThumbnailOffset) { 1893 throw new IOException("Corrupted image"); 1894 } 1895 byte[] buffer = new byte[mThumbnailLength]; 1896 if (in.read(buffer) != mThumbnailLength) { 1897 throw new IOException("Corrupted image"); 1898 } 1899 mThumbnailBytes = buffer; 1900 return buffer; 1901 } catch (IOException | ErrnoException e) { 1902 // Couldn't get a thumbnail image. 1903 Log.d(TAG, "Encountered exception while getting thumbnail", e); 1904 } finally { 1905 IoUtils.closeQuietly(in); 1906 } 1907 return null; 1908 } 1909 1910 /** 1911 * Creates and returns a Bitmap object of the thumbnail image based on the byte array and the 1912 * thumbnail compression value, or {@code null} if the compression type is unsupported. 1913 */ 1914 public Bitmap getThumbnailBitmap() { 1915 if (!mHasThumbnail) { 1916 return null; 1917 } else if (mThumbnailBytes == null) { 1918 mThumbnailBytes = getThumbnailBytes(); 1919 } 1920 1921 if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { 1922 return BitmapFactory.decodeByteArray(mThumbnailBytes, 0, mThumbnailLength); 1923 } else if (mThumbnailCompression == DATA_UNCOMPRESSED) { 1924 int[] rgbValues = new int[mThumbnailBytes.length / 3]; 1925 byte alpha = (byte) 0xff000000; 1926 for (int i = 0; i < rgbValues.length; i++) { 1927 rgbValues[i] = alpha + (mThumbnailBytes[3 * i] << 16) 1928 + (mThumbnailBytes[3 * i + 1] << 8) + mThumbnailBytes[3 * i + 2]; 1929 } 1930 1931 ExifAttribute imageLengthAttribute = 1932 (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_LENGTH); 1933 ExifAttribute imageWidthAttribute = 1934 (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_WIDTH); 1935 if (imageLengthAttribute != null && imageWidthAttribute != null) { 1936 int imageLength = imageLengthAttribute.getIntValue(mExifByteOrder); 1937 int imageWidth = imageWidthAttribute.getIntValue(mExifByteOrder); 1938 return Bitmap.createBitmap( 1939 rgbValues, imageWidth, imageLength, Bitmap.Config.ARGB_8888); 1940 } 1941 } 1942 return null; 1943 } 1944 1945 /** 1946 * Returns true if thumbnail image is JPEG Compressed, or false if either thumbnail image does 1947 * not exist or thumbnail image is uncompressed. 1948 */ 1949 public boolean isThumbnailCompressed() { 1950 if (!mHasThumbnail) { 1951 return false; 1952 } 1953 if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { 1954 return true; 1955 } 1956 return false; 1957 } 1958 1959 /** 1960 * Returns the offset and length of thumbnail inside the image file, or 1961 * {@code null} if there is no thumbnail. 1962 * 1963 * @return two-element array, the offset in the first value, and length in 1964 * the second, or {@code null} if no thumbnail was found. 1965 */ 1966 public long[] getThumbnailRange() { 1967 if (!mHasThumbnail) { 1968 return null; 1969 } 1970 1971 long[] range = new long[2]; 1972 range[0] = mThumbnailOffset; 1973 range[1] = mThumbnailLength; 1974 1975 return range; 1976 } 1977 1978 /** 1979 * Stores the latitude and longitude value in a float array. The first element is 1980 * the latitude, and the second element is the longitude. Returns false if the 1981 * Exif tags are not available. 1982 */ 1983 public boolean getLatLong(float output[]) { 1984 String latValue = getAttribute(TAG_GPS_LATITUDE); 1985 String latRef = getAttribute(TAG_GPS_LATITUDE_REF); 1986 String lngValue = getAttribute(TAG_GPS_LONGITUDE); 1987 String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF); 1988 1989 if (latValue != null && latRef != null && lngValue != null && lngRef != null) { 1990 try { 1991 output[0] = convertRationalLatLonToFloat(latValue, latRef); 1992 output[1] = convertRationalLatLonToFloat(lngValue, lngRef); 1993 return true; 1994 } catch (IllegalArgumentException e) { 1995 // if values are not parseable 1996 } 1997 } 1998 1999 return false; 2000 } 2001 2002 /** 2003 * Return the altitude in meters. If the exif tag does not exist, return 2004 * <var>defaultValue</var>. 2005 * 2006 * @param defaultValue the value to return if the tag is not available. 2007 */ 2008 public double getAltitude(double defaultValue) { 2009 double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1); 2010 int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1); 2011 2012 if (altitude >= 0 && ref >= 0) { 2013 return (altitude * ((ref == 1) ? -1 : 1)); 2014 } else { 2015 return defaultValue; 2016 } 2017 } 2018 2019 /** 2020 * Returns number of milliseconds since Jan. 1, 1970, midnight local time. 2021 * Returns -1 if the date time information if not available. 2022 * @hide 2023 */ 2024 public long getDateTime() { 2025 String dateTimeString = getAttribute(TAG_DATETIME); 2026 if (dateTimeString == null 2027 || !sNonZeroTimePattern.matcher(dateTimeString).matches()) return -1; 2028 2029 ParsePosition pos = new ParsePosition(0); 2030 try { 2031 // The exif field is in local time. Parsing it as if it is UTC will yield time 2032 // since 1/1/1970 local time 2033 Date datetime = sFormatter.parse(dateTimeString, pos); 2034 if (datetime == null) return -1; 2035 long msecs = datetime.getTime(); 2036 2037 String subSecs = getAttribute(TAG_SUBSEC_TIME); 2038 if (subSecs != null) { 2039 try { 2040 long sub = Long.parseLong(subSecs); 2041 while (sub > 1000) { 2042 sub /= 10; 2043 } 2044 msecs += sub; 2045 } catch (NumberFormatException e) { 2046 // Ignored 2047 } 2048 } 2049 return msecs; 2050 } catch (IllegalArgumentException e) { 2051 return -1; 2052 } 2053 } 2054 2055 /** 2056 * Returns number of milliseconds since Jan. 1, 1970, midnight UTC. 2057 * Returns -1 if the date time information if not available. 2058 * @hide 2059 */ 2060 public long getGpsDateTime() { 2061 String date = getAttribute(TAG_GPS_DATESTAMP); 2062 String time = getAttribute(TAG_GPS_TIMESTAMP); 2063 if (date == null || time == null 2064 || (!sNonZeroTimePattern.matcher(date).matches() 2065 && !sNonZeroTimePattern.matcher(time).matches())) { 2066 return -1; 2067 } 2068 2069 String dateTimeString = date + ' ' + time; 2070 2071 ParsePosition pos = new ParsePosition(0); 2072 try { 2073 Date datetime = sFormatter.parse(dateTimeString, pos); 2074 if (datetime == null) return -1; 2075 return datetime.getTime(); 2076 } catch (IllegalArgumentException e) { 2077 return -1; 2078 } 2079 } 2080 2081 /** {@hide} */ 2082 public static float convertRationalLatLonToFloat(String rationalString, String ref) { 2083 try { 2084 String [] parts = rationalString.split(","); 2085 2086 String [] pair; 2087 pair = parts[0].split("/"); 2088 double degrees = Double.parseDouble(pair[0].trim()) 2089 / Double.parseDouble(pair[1].trim()); 2090 2091 pair = parts[1].split("/"); 2092 double minutes = Double.parseDouble(pair[0].trim()) 2093 / Double.parseDouble(pair[1].trim()); 2094 2095 pair = parts[2].split("/"); 2096 double seconds = Double.parseDouble(pair[0].trim()) 2097 / Double.parseDouble(pair[1].trim()); 2098 2099 double result = degrees + (minutes / 60.0) + (seconds / 3600.0); 2100 if ((ref.equals("S") || ref.equals("W"))) { 2101 return (float) -result; 2102 } 2103 return (float) result; 2104 } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { 2105 // Not valid 2106 throw new IllegalArgumentException(); 2107 } 2108 } 2109 2110 // Checks the type of image file 2111 private int getMimeType(BufferedInputStream in) throws IOException { 2112 in.mark(SIGNATURE_CHECK_SIZE); 2113 byte[] signatureCheckBytes = new byte[SIGNATURE_CHECK_SIZE]; 2114 in.read(signatureCheckBytes); 2115 in.reset(); 2116 if (isJpegFormat(signatureCheckBytes)) { 2117 return IMAGE_TYPE_JPEG; 2118 } else if (isRafFormat(signatureCheckBytes)) { 2119 return IMAGE_TYPE_RAF; 2120 } else if (isHeifFormat(signatureCheckBytes)) { 2121 return IMAGE_TYPE_HEIF; 2122 } else if (isOrfFormat(signatureCheckBytes)) { 2123 return IMAGE_TYPE_ORF; 2124 } else if (isRw2Format(signatureCheckBytes)) { 2125 return IMAGE_TYPE_RW2; 2126 } 2127 // Certain file formats (PEF) are identified in readImageFileDirectory() 2128 return IMAGE_TYPE_UNKNOWN; 2129 } 2130 2131 /** 2132 * This method looks at the first 3 bytes to determine if this file is a JPEG file. 2133 * See http://www.media.mit.edu/pia/Research/deepview/exif.html, "JPEG format and Marker" 2134 */ 2135 private static boolean isJpegFormat(byte[] signatureCheckBytes) throws IOException { 2136 for (int i = 0; i < JPEG_SIGNATURE.length; i++) { 2137 if (signatureCheckBytes[i] != JPEG_SIGNATURE[i]) { 2138 return false; 2139 } 2140 } 2141 return true; 2142 } 2143 2144 /** 2145 * This method looks at the first 15 bytes to determine if this file is a RAF file. 2146 * There is no official specification for RAF files from Fuji, but there is an online archive of 2147 * image file specifications: 2148 * http://fileformats.archiveteam.org/wiki/Fujifilm_RAF 2149 */ 2150 private boolean isRafFormat(byte[] signatureCheckBytes) throws IOException { 2151 byte[] rafSignatureBytes = RAF_SIGNATURE.getBytes(); 2152 for (int i = 0; i < rafSignatureBytes.length; i++) { 2153 if (signatureCheckBytes[i] != rafSignatureBytes[i]) { 2154 return false; 2155 } 2156 } 2157 return true; 2158 } 2159 2160 private boolean isHeifFormat(byte[] signatureCheckBytes) throws IOException { 2161 ByteOrderedDataInputStream signatureInputStream = null; 2162 try { 2163 signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes); 2164 signatureInputStream.setByteOrder(ByteOrder.BIG_ENDIAN); 2165 2166 long chunkSize = signatureInputStream.readInt(); 2167 byte[] chunkType = new byte[4]; 2168 signatureInputStream.read(chunkType); 2169 2170 if (!Arrays.equals(chunkType, HEIF_TYPE_FTYP)) { 2171 return false; 2172 } 2173 2174 long chunkDataOffset = 8; 2175 if (chunkSize == 1) { 2176 // This indicates that the next 8 bytes represent the chunk size, 2177 // and chunk data comes after that. 2178 chunkSize = signatureInputStream.readLong(); 2179 if (chunkSize < 16) { 2180 // The smallest valid chunk is 16 bytes long in this case. 2181 return false; 2182 } 2183 chunkDataOffset += 8; 2184 } 2185 2186 // only sniff up to signatureCheckBytes.length 2187 if (chunkSize > signatureCheckBytes.length) { 2188 chunkSize = signatureCheckBytes.length; 2189 } 2190 2191 long chunkDataSize = chunkSize - chunkDataOffset; 2192 2193 // It should at least have major brand (4-byte) and minor version (4-byte). 2194 // The rest of the chunk (if any) is a list of (4-byte) compatible brands. 2195 if (chunkDataSize < 8) { 2196 return false; 2197 } 2198 2199 byte[] brand = new byte[4]; 2200 boolean isMif1 = false; 2201 boolean isHeic = false; 2202 for (long i = 0; i < chunkDataSize / 4; ++i) { 2203 if (signatureInputStream.read(brand) != brand.length) { 2204 return false; 2205 } 2206 if (i == 1) { 2207 // Skip this index, it refers to the minorVersion, not a brand. 2208 continue; 2209 } 2210 if (Arrays.equals(brand, HEIF_BRAND_MIF1)) { 2211 isMif1 = true; 2212 } else if (Arrays.equals(brand, HEIF_BRAND_HEIC)) { 2213 isHeic = true; 2214 } 2215 if (isMif1 && isHeic) { 2216 return true; 2217 } 2218 } 2219 } catch (Exception e) { 2220 if (DEBUG) { 2221 Log.d(TAG, "Exception parsing HEIF file type box.", e); 2222 } 2223 } finally { 2224 if (signatureInputStream != null) { 2225 signatureInputStream.close(); 2226 signatureInputStream = null; 2227 } 2228 } 2229 return false; 2230 } 2231 2232 /** 2233 * ORF has a similar structure to TIFF but it contains a different signature at the TIFF Header. 2234 * This method looks at the 2 bytes following the Byte Order bytes to determine if this file is 2235 * an ORF file. 2236 * There is no official specification for ORF files from Olympus, but there is an online archive 2237 * of image file specifications: 2238 * http://fileformats.archiveteam.org/wiki/Olympus_ORF 2239 */ 2240 private boolean isOrfFormat(byte[] signatureCheckBytes) throws IOException { 2241 ByteOrderedDataInputStream signatureInputStream = 2242 new ByteOrderedDataInputStream(signatureCheckBytes); 2243 // Read byte order 2244 mExifByteOrder = readByteOrder(signatureInputStream); 2245 // Set byte order 2246 signatureInputStream.setByteOrder(mExifByteOrder); 2247 2248 short orfSignature = signatureInputStream.readShort(); 2249 if (orfSignature == ORF_SIGNATURE_1 || orfSignature == ORF_SIGNATURE_2) { 2250 return true; 2251 } 2252 return false; 2253 } 2254 2255 /** 2256 * RW2 is TIFF-based, but stores 0x55 signature byte instead of 0x42 at the header 2257 * See http://lclevy.free.fr/raw/ 2258 */ 2259 private boolean isRw2Format(byte[] signatureCheckBytes) throws IOException { 2260 ByteOrderedDataInputStream signatureInputStream = 2261 new ByteOrderedDataInputStream(signatureCheckBytes); 2262 // Read byte order 2263 mExifByteOrder = readByteOrder(signatureInputStream); 2264 // Set byte order 2265 signatureInputStream.setByteOrder(mExifByteOrder); 2266 2267 short signatureByte = signatureInputStream.readShort(); 2268 if (signatureByte == RW2_SIGNATURE) { 2269 return true; 2270 } 2271 return false; 2272 } 2273 2274 /** 2275 * Loads EXIF attributes from a JPEG input stream. 2276 * 2277 * @param in The input stream that starts with the JPEG data. 2278 * @param jpegOffset The offset value in input stream for JPEG data. 2279 * @param imageType The image type from which to retrieve metadata. Use IFD_TYPE_PRIMARY for 2280 * primary image, IFD_TYPE_PREVIEW for preview image, and 2281 * IFD_TYPE_THUMBNAIL for thumbnail image. 2282 * @throws IOException If the data contains invalid JPEG markers, offsets, or length values. 2283 */ 2284 private void getJpegAttributes(ByteOrderedDataInputStream in, int jpegOffset, int imageType) 2285 throws IOException { 2286 // See JPEG File Interchange Format Specification, "JFIF Specification" 2287 if (DEBUG) { 2288 Log.d(TAG, "getJpegAttributes starting with: " + in); 2289 } 2290 2291 // JPEG uses Big Endian by default. See https://people.cs.umass.edu/~verts/cs32/endian.html 2292 in.setByteOrder(ByteOrder.BIG_ENDIAN); 2293 2294 // Skip to JPEG data 2295 in.seek(jpegOffset); 2296 int bytesRead = jpegOffset; 2297 2298 byte marker; 2299 if ((marker = in.readByte()) != MARKER) { 2300 throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); 2301 } 2302 ++bytesRead; 2303 if (in.readByte() != MARKER_SOI) { 2304 throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); 2305 } 2306 ++bytesRead; 2307 while (true) { 2308 marker = in.readByte(); 2309 if (marker != MARKER) { 2310 throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff)); 2311 } 2312 ++bytesRead; 2313 marker = in.readByte(); 2314 if (DEBUG) { 2315 Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff)); 2316 } 2317 ++bytesRead; 2318 2319 // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and 2320 // the image data will terminate right after. 2321 if (marker == MARKER_EOI || marker == MARKER_SOS) { 2322 break; 2323 } 2324 int length = in.readUnsignedShort() - 2; 2325 bytesRead += 2; 2326 if (DEBUG) { 2327 Log.d(TAG, "JPEG segment: " + Integer.toHexString(marker & 0xff) + " (length: " 2328 + (length + 2) + ")"); 2329 } 2330 if (length < 0) { 2331 throw new IOException("Invalid length"); 2332 } 2333 switch (marker) { 2334 case MARKER_APP1: { 2335 if (DEBUG) { 2336 Log.d(TAG, "MARKER_APP1"); 2337 } 2338 if (length < 6) { 2339 // Skip if it's not an EXIF APP1 segment. 2340 break; 2341 } 2342 byte[] identifier = new byte[6]; 2343 if (in.read(identifier) != 6) { 2344 throw new IOException("Invalid exif"); 2345 } 2346 bytesRead += 6; 2347 length -= 6; 2348 if (!Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) { 2349 // Skip if it's not an EXIF APP1 segment. 2350 break; 2351 } 2352 if (length <= 0) { 2353 throw new IOException("Invalid exif"); 2354 } 2355 if (DEBUG) { 2356 Log.d(TAG, "readExifSegment with a byte array (length: " + length + ")"); 2357 } 2358 // Save offset values for createJpegThumbnailBitmap() function 2359 mExifOffset = bytesRead; 2360 2361 byte[] bytes = new byte[length]; 2362 if (in.read(bytes) != length) { 2363 throw new IOException("Invalid exif"); 2364 } 2365 bytesRead += length; 2366 length = 0; 2367 2368 readExifSegment(bytes, imageType); 2369 break; 2370 } 2371 2372 case MARKER_COM: { 2373 byte[] bytes = new byte[length]; 2374 if (in.read(bytes) != length) { 2375 throw new IOException("Invalid exif"); 2376 } 2377 length = 0; 2378 if (getAttribute(TAG_USER_COMMENT) == null) { 2379 mAttributes[IFD_TYPE_EXIF].put(TAG_USER_COMMENT, ExifAttribute.createString( 2380 new String(bytes, ASCII))); 2381 } 2382 break; 2383 } 2384 2385 case MARKER_SOF0: 2386 case MARKER_SOF1: 2387 case MARKER_SOF2: 2388 case MARKER_SOF3: 2389 case MARKER_SOF5: 2390 case MARKER_SOF6: 2391 case MARKER_SOF7: 2392 case MARKER_SOF9: 2393 case MARKER_SOF10: 2394 case MARKER_SOF11: 2395 case MARKER_SOF13: 2396 case MARKER_SOF14: 2397 case MARKER_SOF15: { 2398 if (in.skipBytes(1) != 1) { 2399 throw new IOException("Invalid SOFx"); 2400 } 2401 mAttributes[imageType].put(TAG_IMAGE_LENGTH, ExifAttribute.createULong( 2402 in.readUnsignedShort(), mExifByteOrder)); 2403 mAttributes[imageType].put(TAG_IMAGE_WIDTH, ExifAttribute.createULong( 2404 in.readUnsignedShort(), mExifByteOrder)); 2405 length -= 5; 2406 break; 2407 } 2408 2409 default: { 2410 break; 2411 } 2412 } 2413 if (length < 0) { 2414 throw new IOException("Invalid length"); 2415 } 2416 if (in.skipBytes(length) != length) { 2417 throw new IOException("Invalid JPEG segment"); 2418 } 2419 bytesRead += length; 2420 } 2421 // Restore original byte order 2422 in.setByteOrder(mExifByteOrder); 2423 } 2424 2425 private void getRawAttributes(ByteOrderedDataInputStream in) throws IOException { 2426 // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. 2427 parseTiffHeaders(in, in.available()); 2428 2429 // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6. 2430 readImageFileDirectory(in, IFD_TYPE_PRIMARY); 2431 2432 // Update ImageLength/Width tags for all image data. 2433 updateImageSizeValues(in, IFD_TYPE_PRIMARY); 2434 updateImageSizeValues(in, IFD_TYPE_PREVIEW); 2435 updateImageSizeValues(in, IFD_TYPE_THUMBNAIL); 2436 2437 // Check if each image data is in valid position. 2438 validateImages(in); 2439 2440 if (mMimeType == IMAGE_TYPE_PEF) { 2441 // PEF files contain a MakerNote data, which contains the data for ColorSpace tag. 2442 // See http://lclevy.free.fr/raw/ and piex.cc PefGetPreviewData() 2443 ExifAttribute makerNoteAttribute = 2444 (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE); 2445 if (makerNoteAttribute != null) { 2446 // Create an ordered DataInputStream for MakerNote 2447 ByteOrderedDataInputStream makerNoteDataInputStream = 2448 new ByteOrderedDataInputStream(makerNoteAttribute.bytes); 2449 makerNoteDataInputStream.setByteOrder(mExifByteOrder); 2450 2451 // Seek to MakerNote data 2452 makerNoteDataInputStream.seek(PEF_MAKER_NOTE_SKIP_SIZE); 2453 2454 // Read IFD data from MakerNote 2455 readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_PEF); 2456 2457 // Update ColorSpace tag 2458 ExifAttribute colorSpaceAttribute = 2459 (ExifAttribute) mAttributes[IFD_TYPE_PEF].get(TAG_COLOR_SPACE); 2460 if (colorSpaceAttribute != null) { 2461 mAttributes[IFD_TYPE_EXIF].put(TAG_COLOR_SPACE, colorSpaceAttribute); 2462 } 2463 } 2464 } 2465 } 2466 2467 /** 2468 * RAF files contains a JPEG and a CFA data. 2469 * The JPEG contains two images, a preview and a thumbnail, while the CFA contains a RAW image. 2470 * This method looks at the first 160 bytes of a RAF file to retrieve the offset and length 2471 * values for the JPEG and CFA data. 2472 * Using that data, it parses the JPEG data to retrieve the preview and thumbnail image data, 2473 * then parses the CFA metadata to retrieve the primary image length/width values. 2474 * For data format details, see http://fileformats.archiveteam.org/wiki/Fujifilm_RAF 2475 */ 2476 private void getRafAttributes(ByteOrderedDataInputStream in) throws IOException { 2477 // Retrieve offset & length values 2478 in.skipBytes(RAF_OFFSET_TO_JPEG_IMAGE_OFFSET); 2479 byte[] jpegOffsetBytes = new byte[4]; 2480 byte[] cfaHeaderOffsetBytes = new byte[4]; 2481 in.read(jpegOffsetBytes); 2482 // Skip JPEG length value since it is not needed 2483 in.skipBytes(RAF_JPEG_LENGTH_VALUE_SIZE); 2484 in.read(cfaHeaderOffsetBytes); 2485 int rafJpegOffset = ByteBuffer.wrap(jpegOffsetBytes).getInt(); 2486 int rafCfaHeaderOffset = ByteBuffer.wrap(cfaHeaderOffsetBytes).getInt(); 2487 2488 // Retrieve JPEG image metadata 2489 getJpegAttributes(in, rafJpegOffset, IFD_TYPE_PREVIEW); 2490 2491 // Skip to CFA header offset. 2492 in.seek(rafCfaHeaderOffset); 2493 2494 // Retrieve primary image length/width values, if TAG_RAF_IMAGE_SIZE exists 2495 in.setByteOrder(ByteOrder.BIG_ENDIAN); 2496 int numberOfDirectoryEntry = in.readInt(); 2497 if (DEBUG) { 2498 Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry); 2499 } 2500 // CFA stores some metadata about the RAW image. Since CFA uses proprietary tags, can only 2501 // find and retrieve image size information tags, while skipping others. 2502 // See piex.cc RafGetDimension() 2503 for (int i = 0; i < numberOfDirectoryEntry; ++i) { 2504 int tagNumber = in.readUnsignedShort(); 2505 int numberOfBytes = in.readUnsignedShort(); 2506 if (tagNumber == TAG_RAF_IMAGE_SIZE.number) { 2507 int imageLength = in.readShort(); 2508 int imageWidth = in.readShort(); 2509 ExifAttribute imageLengthAttribute = 2510 ExifAttribute.createUShort(imageLength, mExifByteOrder); 2511 ExifAttribute imageWidthAttribute = 2512 ExifAttribute.createUShort(imageWidth, mExifByteOrder); 2513 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, imageLengthAttribute); 2514 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, imageWidthAttribute); 2515 if (DEBUG) { 2516 Log.d(TAG, "Updated to length: " + imageLength + ", width: " + imageWidth); 2517 } 2518 return; 2519 } 2520 in.skipBytes(numberOfBytes); 2521 } 2522 } 2523 2524 private void getHeifAttributes(ByteOrderedDataInputStream in) throws IOException { 2525 MediaMetadataRetriever retriever = new MediaMetadataRetriever(); 2526 try { 2527 if (mSeekableFileDescriptor != null) { 2528 retriever.setDataSource(mSeekableFileDescriptor); 2529 } else { 2530 retriever.setDataSource(new MediaDataSource() { 2531 long mPosition; 2532 2533 @Override 2534 public void close() throws IOException {} 2535 2536 @Override 2537 public int readAt(long position, byte[] buffer, int offset, int size) 2538 throws IOException { 2539 if (size == 0) { 2540 return 0; 2541 } 2542 if (position < 0) { 2543 return -1; 2544 } 2545 if (mPosition != position) { 2546 in.seek(position); 2547 mPosition = position; 2548 } 2549 2550 int bytesRead = in.read(buffer, offset, size); 2551 if (bytesRead < 0) { 2552 mPosition = -1; // need to seek on next read 2553 return -1; 2554 } 2555 2556 mPosition += bytesRead; 2557 return bytesRead; 2558 } 2559 2560 @Override 2561 public long getSize() throws IOException { 2562 return -1; 2563 } 2564 }); 2565 } 2566 2567 String hasImage = retriever.extractMetadata( 2568 MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE); 2569 String hasVideo = retriever.extractMetadata( 2570 MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO); 2571 2572 String width = null; 2573 String height = null; 2574 String rotation = null; 2575 final String METADATA_VALUE_YES = "yes"; 2576 // If the file has both image and video, prefer image info over video info. 2577 // App querying ExifInterface is most likely using the bitmap path which 2578 // picks the image first. 2579 if (METADATA_VALUE_YES.equals(hasImage)) { 2580 width = retriever.extractMetadata( 2581 MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH); 2582 height = retriever.extractMetadata( 2583 MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT); 2584 rotation = retriever.extractMetadata( 2585 MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION); 2586 } else if (METADATA_VALUE_YES.equals(hasVideo)) { 2587 width = retriever.extractMetadata( 2588 MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); 2589 height = retriever.extractMetadata( 2590 MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); 2591 rotation = retriever.extractMetadata( 2592 MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); 2593 } 2594 2595 if (width != null) { 2596 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, 2597 ExifAttribute.createUShort(Integer.parseInt(width), mExifByteOrder)); 2598 } 2599 2600 if (height != null) { 2601 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, 2602 ExifAttribute.createUShort(Integer.parseInt(height), mExifByteOrder)); 2603 } 2604 2605 if (rotation != null) { 2606 int orientation = ExifInterface.ORIENTATION_NORMAL; 2607 2608 // all rotation angles in CW 2609 switch (Integer.parseInt(rotation)) { 2610 case 90: 2611 orientation = ExifInterface.ORIENTATION_ROTATE_90; 2612 break; 2613 case 180: 2614 orientation = ExifInterface.ORIENTATION_ROTATE_180; 2615 break; 2616 case 270: 2617 orientation = ExifInterface.ORIENTATION_ROTATE_270; 2618 break; 2619 } 2620 2621 mAttributes[IFD_TYPE_PRIMARY].put(TAG_ORIENTATION, 2622 ExifAttribute.createUShort(orientation, mExifByteOrder)); 2623 } 2624 2625 if (DEBUG) { 2626 Log.d(TAG, "Heif meta: " + width + "x" + height + ", rotation " + rotation); 2627 } 2628 } finally { 2629 retriever.release(); 2630 } 2631 } 2632 2633 /** 2634 * ORF files contains a primary image data and a MakerNote data that contains preview/thumbnail 2635 * images. Both data takes the form of IFDs and can therefore be read with the 2636 * readImageFileDirectory() method. 2637 * This method reads all the necessary data and updates the primary/preview/thumbnail image 2638 * information according to the GetOlympusPreviewImage() method in piex.cc. 2639 * For data format details, see the following: 2640 * http://fileformats.archiveteam.org/wiki/Olympus_ORF 2641 * https://libopenraw.freedesktop.org/wiki/Olympus_ORF 2642 */ 2643 private void getOrfAttributes(ByteOrderedDataInputStream in) throws IOException { 2644 // Retrieve primary image data 2645 // Other Exif data will be located in the Makernote. 2646 getRawAttributes(in); 2647 2648 // Additionally retrieve preview/thumbnail information from MakerNote tag, which contains 2649 // proprietary tags and therefore does not have offical documentation 2650 // See GetOlympusPreviewImage() in piex.cc & http://www.exiv2.org/tags-olympus.html 2651 ExifAttribute makerNoteAttribute = 2652 (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE); 2653 if (makerNoteAttribute != null) { 2654 // Create an ordered DataInputStream for MakerNote 2655 ByteOrderedDataInputStream makerNoteDataInputStream = 2656 new ByteOrderedDataInputStream(makerNoteAttribute.bytes); 2657 makerNoteDataInputStream.setByteOrder(mExifByteOrder); 2658 2659 // There are two types of headers for Olympus MakerNotes 2660 // See http://www.exiv2.org/makernote.html#R1 2661 byte[] makerNoteHeader1Bytes = new byte[ORF_MAKER_NOTE_HEADER_1.length]; 2662 makerNoteDataInputStream.readFully(makerNoteHeader1Bytes); 2663 makerNoteDataInputStream.seek(0); 2664 byte[] makerNoteHeader2Bytes = new byte[ORF_MAKER_NOTE_HEADER_2.length]; 2665 makerNoteDataInputStream.readFully(makerNoteHeader2Bytes); 2666 // Skip the corresponding amount of bytes for each header type 2667 if (Arrays.equals(makerNoteHeader1Bytes, ORF_MAKER_NOTE_HEADER_1)) { 2668 makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_1_SIZE); 2669 } else if (Arrays.equals(makerNoteHeader2Bytes, ORF_MAKER_NOTE_HEADER_2)) { 2670 makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_2_SIZE); 2671 } 2672 2673 // Read IFD data from MakerNote 2674 readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_ORF_MAKER_NOTE); 2675 2676 // Retrieve & update preview image offset & length values 2677 ExifAttribute imageLengthAttribute = (ExifAttribute) 2678 mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_START); 2679 ExifAttribute bitsPerSampleAttribute = (ExifAttribute) 2680 mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_LENGTH); 2681 2682 if (imageLengthAttribute != null && bitsPerSampleAttribute != null) { 2683 mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT, 2684 imageLengthAttribute); 2685 mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 2686 bitsPerSampleAttribute); 2687 } 2688 2689 // TODO: Check this behavior in other ORF files 2690 // Retrieve primary image length & width values 2691 // See piex.cc GetOlympusPreviewImage() 2692 ExifAttribute aspectFrameAttribute = (ExifAttribute) 2693 mAttributes[IFD_TYPE_ORF_IMAGE_PROCESSING].get(TAG_ORF_ASPECT_FRAME); 2694 if (aspectFrameAttribute != null) { 2695 int[] aspectFrameValues = new int[4]; 2696 aspectFrameValues = (int[]) aspectFrameAttribute.getValue(mExifByteOrder); 2697 if (aspectFrameValues[2] > aspectFrameValues[0] && 2698 aspectFrameValues[3] > aspectFrameValues[1]) { 2699 int primaryImageWidth = aspectFrameValues[2] - aspectFrameValues[0] + 1; 2700 int primaryImageLength = aspectFrameValues[3] - aspectFrameValues[1] + 1; 2701 // Swap width & length values 2702 if (primaryImageWidth < primaryImageLength) { 2703 primaryImageWidth += primaryImageLength; 2704 primaryImageLength = primaryImageWidth - primaryImageLength; 2705 primaryImageWidth -= primaryImageLength; 2706 } 2707 ExifAttribute primaryImageWidthAttribute = 2708 ExifAttribute.createUShort(primaryImageWidth, mExifByteOrder); 2709 ExifAttribute primaryImageLengthAttribute = 2710 ExifAttribute.createUShort(primaryImageLength, mExifByteOrder); 2711 2712 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, primaryImageWidthAttribute); 2713 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, primaryImageLengthAttribute); 2714 } 2715 } 2716 } 2717 } 2718 2719 // RW2 contains the primary image data in IFD0 and the preview and/or thumbnail image data in 2720 // the JpgFromRaw tag 2721 // See https://libopenraw.freedesktop.org/wiki/Panasonic_RAW/ and piex.cc Rw2GetPreviewData() 2722 private void getRw2Attributes(ByteOrderedDataInputStream in) throws IOException { 2723 // Retrieve primary image data 2724 getRawAttributes(in); 2725 2726 // Retrieve preview and/or thumbnail image data 2727 ExifAttribute jpgFromRawAttribute = 2728 (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_JPG_FROM_RAW); 2729 if (jpgFromRawAttribute != null) { 2730 getJpegAttributes(in, mRw2JpgFromRawOffset, IFD_TYPE_PREVIEW); 2731 } 2732 2733 // Set ISO tag value if necessary 2734 ExifAttribute rw2IsoAttribute = 2735 (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_ISO); 2736 ExifAttribute exifIsoAttribute = 2737 (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_ISO_SPEED_RATINGS); 2738 if (rw2IsoAttribute != null && exifIsoAttribute == null) { 2739 // Place this attribute only if it doesn't exist 2740 mAttributes[IFD_TYPE_EXIF].put(TAG_ISO_SPEED_RATINGS, rw2IsoAttribute); 2741 } 2742 } 2743 2744 // Stores a new JPEG image with EXIF attributes into a given output stream. 2745 private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream) 2746 throws IOException { 2747 // See JPEG File Interchange Format Specification, "JFIF Specification" 2748 if (DEBUG) { 2749 Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream 2750 + ", outputStream: " + outputStream + ")"); 2751 } 2752 DataInputStream dataInputStream = new DataInputStream(inputStream); 2753 ByteOrderedDataOutputStream dataOutputStream = 2754 new ByteOrderedDataOutputStream(outputStream, ByteOrder.BIG_ENDIAN); 2755 if (dataInputStream.readByte() != MARKER) { 2756 throw new IOException("Invalid marker"); 2757 } 2758 dataOutputStream.writeByte(MARKER); 2759 if (dataInputStream.readByte() != MARKER_SOI) { 2760 throw new IOException("Invalid marker"); 2761 } 2762 dataOutputStream.writeByte(MARKER_SOI); 2763 2764 // Write EXIF APP1 segment 2765 dataOutputStream.writeByte(MARKER); 2766 dataOutputStream.writeByte(MARKER_APP1); 2767 writeExifSegment(dataOutputStream, 6); 2768 2769 byte[] bytes = new byte[4096]; 2770 2771 while (true) { 2772 byte marker = dataInputStream.readByte(); 2773 if (marker != MARKER) { 2774 throw new IOException("Invalid marker"); 2775 } 2776 marker = dataInputStream.readByte(); 2777 switch (marker) { 2778 case MARKER_APP1: { 2779 int length = dataInputStream.readUnsignedShort() - 2; 2780 if (length < 0) { 2781 throw new IOException("Invalid length"); 2782 } 2783 byte[] identifier = new byte[6]; 2784 if (length >= 6) { 2785 if (dataInputStream.read(identifier) != 6) { 2786 throw new IOException("Invalid exif"); 2787 } 2788 if (Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) { 2789 // Skip the original EXIF APP1 segment. 2790 if (dataInputStream.skipBytes(length - 6) != length - 6) { 2791 throw new IOException("Invalid length"); 2792 } 2793 break; 2794 } 2795 } 2796 // Copy non-EXIF APP1 segment. 2797 dataOutputStream.writeByte(MARKER); 2798 dataOutputStream.writeByte(marker); 2799 dataOutputStream.writeUnsignedShort(length + 2); 2800 if (length >= 6) { 2801 length -= 6; 2802 dataOutputStream.write(identifier); 2803 } 2804 int read; 2805 while (length > 0 && (read = dataInputStream.read( 2806 bytes, 0, Math.min(length, bytes.length))) >= 0) { 2807 dataOutputStream.write(bytes, 0, read); 2808 length -= read; 2809 } 2810 break; 2811 } 2812 case MARKER_EOI: 2813 case MARKER_SOS: { 2814 dataOutputStream.writeByte(MARKER); 2815 dataOutputStream.writeByte(marker); 2816 // Copy all the remaining data 2817 Streams.copy(dataInputStream, dataOutputStream); 2818 return; 2819 } 2820 default: { 2821 // Copy JPEG segment 2822 dataOutputStream.writeByte(MARKER); 2823 dataOutputStream.writeByte(marker); 2824 int length = dataInputStream.readUnsignedShort(); 2825 dataOutputStream.writeUnsignedShort(length); 2826 length -= 2; 2827 if (length < 0) { 2828 throw new IOException("Invalid length"); 2829 } 2830 int read; 2831 while (length > 0 && (read = dataInputStream.read( 2832 bytes, 0, Math.min(length, bytes.length))) >= 0) { 2833 dataOutputStream.write(bytes, 0, read); 2834 length -= read; 2835 } 2836 break; 2837 } 2838 } 2839 } 2840 } 2841 2842 // Reads the given EXIF byte area and save its tag data into attributes. 2843 private void readExifSegment(byte[] exifBytes, int imageType) throws IOException { 2844 ByteOrderedDataInputStream dataInputStream = 2845 new ByteOrderedDataInputStream(exifBytes); 2846 2847 // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. 2848 parseTiffHeaders(dataInputStream, exifBytes.length); 2849 2850 // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6. 2851 readImageFileDirectory(dataInputStream, imageType); 2852 } 2853 2854 private void addDefaultValuesForCompatibility() { 2855 // If DATETIME tag has no value, then set the value to DATETIME_ORIGINAL tag's. 2856 String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL); 2857 if (valueOfDateTimeOriginal != null && getAttribute(TAG_DATETIME) == null) { 2858 mAttributes[IFD_TYPE_PRIMARY].put(TAG_DATETIME, 2859 ExifAttribute.createString(valueOfDateTimeOriginal)); 2860 } 2861 2862 // Add the default value. 2863 if (getAttribute(TAG_IMAGE_WIDTH) == null) { 2864 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, 2865 ExifAttribute.createULong(0, mExifByteOrder)); 2866 } 2867 if (getAttribute(TAG_IMAGE_LENGTH) == null) { 2868 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, 2869 ExifAttribute.createULong(0, mExifByteOrder)); 2870 } 2871 if (getAttribute(TAG_ORIENTATION) == null) { 2872 mAttributes[IFD_TYPE_PRIMARY].put(TAG_ORIENTATION, 2873 ExifAttribute.createUShort(0, mExifByteOrder)); 2874 } 2875 if (getAttribute(TAG_LIGHT_SOURCE) == null) { 2876 mAttributes[IFD_TYPE_EXIF].put(TAG_LIGHT_SOURCE, 2877 ExifAttribute.createULong(0, mExifByteOrder)); 2878 } 2879 } 2880 2881 private ByteOrder readByteOrder(ByteOrderedDataInputStream dataInputStream) 2882 throws IOException { 2883 // Read byte order. 2884 short byteOrder = dataInputStream.readShort(); 2885 switch (byteOrder) { 2886 case BYTE_ALIGN_II: 2887 if (DEBUG) { 2888 Log.d(TAG, "readExifSegment: Byte Align II"); 2889 } 2890 return ByteOrder.LITTLE_ENDIAN; 2891 case BYTE_ALIGN_MM: 2892 if (DEBUG) { 2893 Log.d(TAG, "readExifSegment: Byte Align MM"); 2894 } 2895 return ByteOrder.BIG_ENDIAN; 2896 default: 2897 throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder)); 2898 } 2899 } 2900 2901 private void parseTiffHeaders(ByteOrderedDataInputStream dataInputStream, 2902 int exifBytesLength) throws IOException { 2903 // Read byte order 2904 mExifByteOrder = readByteOrder(dataInputStream); 2905 // Set byte order 2906 dataInputStream.setByteOrder(mExifByteOrder); 2907 2908 // Check start code 2909 int startCode = dataInputStream.readUnsignedShort(); 2910 if (mMimeType != IMAGE_TYPE_ORF && mMimeType != IMAGE_TYPE_RW2 && startCode != START_CODE) { 2911 throw new IOException("Invalid start code: " + Integer.toHexString(startCode)); 2912 } 2913 2914 // Read and skip to first ifd offset 2915 int firstIfdOffset = dataInputStream.readInt(); 2916 if (firstIfdOffset < 8 || firstIfdOffset >= exifBytesLength) { 2917 throw new IOException("Invalid first Ifd offset: " + firstIfdOffset); 2918 } 2919 firstIfdOffset -= 8; 2920 if (firstIfdOffset > 0) { 2921 if (dataInputStream.skipBytes(firstIfdOffset) != firstIfdOffset) { 2922 throw new IOException("Couldn't jump to first Ifd: " + firstIfdOffset); 2923 } 2924 } 2925 } 2926 2927 // Reads image file directory, which is a tag group in EXIF. 2928 private void readImageFileDirectory(ByteOrderedDataInputStream dataInputStream, 2929 @IfdType int ifdType) throws IOException { 2930 if (dataInputStream.mPosition + 2 > dataInputStream.mLength) { 2931 // Return if there is no data from the offset. 2932 return; 2933 } 2934 // See TIFF 6.0 Section 2: TIFF Structure, Figure 1. 2935 short numberOfDirectoryEntry = dataInputStream.readShort(); 2936 if (dataInputStream.mPosition + 12 * numberOfDirectoryEntry > dataInputStream.mLength) { 2937 // Return if the size of entries is too big. 2938 return; 2939 } 2940 2941 if (DEBUG) { 2942 Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry); 2943 } 2944 2945 // See TIFF 6.0 Section 2: TIFF Structure, "Image File Directory". 2946 for (short i = 0; i < numberOfDirectoryEntry; ++i) { 2947 int tagNumber = dataInputStream.readUnsignedShort(); 2948 int dataFormat = dataInputStream.readUnsignedShort(); 2949 int numberOfComponents = dataInputStream.readInt(); 2950 // Next four bytes is for data offset or value. 2951 long nextEntryOffset = dataInputStream.peek() + 4; 2952 2953 // Look up a corresponding tag from tag number 2954 ExifTag tag = (ExifTag) sExifTagMapsForReading[ifdType].get(tagNumber); 2955 2956 if (DEBUG) { 2957 Log.d(TAG, String.format("ifdType: %d, tagNumber: %d, tagName: %s, dataFormat: %d, " 2958 + "numberOfComponents: %d", ifdType, tagNumber, 2959 tag != null ? tag.name : null, dataFormat, numberOfComponents)); 2960 } 2961 2962 long byteCount = 0; 2963 boolean valid = false; 2964 if (tag == null) { 2965 Log.w(TAG, "Skip the tag entry since tag number is not defined: " + tagNumber); 2966 } else if (dataFormat <= 0 || dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) { 2967 Log.w(TAG, "Skip the tag entry since data format is invalid: " + dataFormat); 2968 } else { 2969 byteCount = (long) numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat]; 2970 if (byteCount < 0 || byteCount > Integer.MAX_VALUE) { 2971 Log.w(TAG, "Skip the tag entry since the number of components is invalid: " 2972 + numberOfComponents); 2973 } else { 2974 valid = true; 2975 } 2976 } 2977 if (!valid) { 2978 dataInputStream.seek(nextEntryOffset); 2979 continue; 2980 } 2981 2982 // Read a value from data field or seek to the value offset which is stored in data 2983 // field if the size of the entry value is bigger than 4. 2984 if (byteCount > 4) { 2985 int offset = dataInputStream.readInt(); 2986 if (DEBUG) { 2987 Log.d(TAG, "seek to data offset: " + offset); 2988 } 2989 if (mMimeType == IMAGE_TYPE_ORF) { 2990 if (tag.name == TAG_MAKER_NOTE) { 2991 // Save offset value for reading thumbnail 2992 mOrfMakerNoteOffset = offset; 2993 } else if (ifdType == IFD_TYPE_ORF_MAKER_NOTE 2994 && tag.name == TAG_ORF_THUMBNAIL_IMAGE) { 2995 // Retrieve & update values for thumbnail offset and length values for ORF 2996 mOrfThumbnailOffset = offset; 2997 mOrfThumbnailLength = numberOfComponents; 2998 2999 ExifAttribute compressionAttribute = 3000 ExifAttribute.createUShort(DATA_JPEG, mExifByteOrder); 3001 ExifAttribute jpegInterchangeFormatAttribute = 3002 ExifAttribute.createULong(mOrfThumbnailOffset, mExifByteOrder); 3003 ExifAttribute jpegInterchangeFormatLengthAttribute = 3004 ExifAttribute.createULong(mOrfThumbnailLength, mExifByteOrder); 3005 3006 mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_COMPRESSION, compressionAttribute); 3007 mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT, 3008 jpegInterchangeFormatAttribute); 3009 mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 3010 jpegInterchangeFormatLengthAttribute); 3011 } 3012 } else if (mMimeType == IMAGE_TYPE_RW2) { 3013 if (tag.name == TAG_RW2_JPG_FROM_RAW) { 3014 mRw2JpgFromRawOffset = offset; 3015 } 3016 } 3017 if (offset + byteCount <= dataInputStream.mLength) { 3018 dataInputStream.seek(offset); 3019 } else { 3020 // Skip if invalid data offset. 3021 Log.w(TAG, "Skip the tag entry since data offset is invalid: " + offset); 3022 dataInputStream.seek(nextEntryOffset); 3023 continue; 3024 } 3025 } 3026 3027 // Recursively parse IFD when a IFD pointer tag appears. 3028 Object nextIfdType = sExifPointerTagMap.get(tagNumber); 3029 if (DEBUG) { 3030 Log.d(TAG, "nextIfdType: " + nextIfdType + " byteCount: " + byteCount); 3031 } 3032 3033 if (nextIfdType != null) { 3034 long offset = -1L; 3035 // Get offset from data field 3036 switch (dataFormat) { 3037 case IFD_FORMAT_USHORT: { 3038 offset = dataInputStream.readUnsignedShort(); 3039 break; 3040 } 3041 case IFD_FORMAT_SSHORT: { 3042 offset = dataInputStream.readShort(); 3043 break; 3044 } 3045 case IFD_FORMAT_ULONG: { 3046 offset = dataInputStream.readUnsignedInt(); 3047 break; 3048 } 3049 case IFD_FORMAT_SLONG: 3050 case IFD_FORMAT_IFD: { 3051 offset = dataInputStream.readInt(); 3052 break; 3053 } 3054 default: { 3055 // Nothing to do 3056 break; 3057 } 3058 } 3059 if (DEBUG) { 3060 Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tag.name)); 3061 } 3062 if (offset > 0L && offset < dataInputStream.mLength) { 3063 dataInputStream.seek(offset); 3064 readImageFileDirectory(dataInputStream, (int) nextIfdType); 3065 } else { 3066 Log.w(TAG, "Skip jump into the IFD since its offset is invalid: " + offset); 3067 } 3068 3069 dataInputStream.seek(nextEntryOffset); 3070 continue; 3071 } 3072 3073 byte[] bytes = new byte[(int) byteCount]; 3074 dataInputStream.readFully(bytes); 3075 ExifAttribute attribute = new ExifAttribute(dataFormat, numberOfComponents, bytes); 3076 mAttributes[ifdType].put(tag.name, attribute); 3077 3078 // DNG files have a DNG Version tag specifying the version of specifications that the 3079 // image file is following. 3080 // See http://fileformats.archiveteam.org/wiki/DNG 3081 if (tag.name == TAG_DNG_VERSION) { 3082 mMimeType = IMAGE_TYPE_DNG; 3083 } 3084 3085 // PEF files have a Make or Model tag that begins with "PENTAX" or a compression tag 3086 // that is 65535. 3087 // See http://fileformats.archiveteam.org/wiki/Pentax_PEF 3088 if (((tag.name == TAG_MAKE || tag.name == TAG_MODEL) 3089 && attribute.getStringValue(mExifByteOrder).contains(PEF_SIGNATURE)) 3090 || (tag.name == TAG_COMPRESSION 3091 && attribute.getIntValue(mExifByteOrder) == 65535)) { 3092 mMimeType = IMAGE_TYPE_PEF; 3093 } 3094 3095 // Seek to next tag offset 3096 if (dataInputStream.peek() != nextEntryOffset) { 3097 dataInputStream.seek(nextEntryOffset); 3098 } 3099 } 3100 3101 if (dataInputStream.peek() + 4 <= dataInputStream.mLength) { 3102 int nextIfdOffset = dataInputStream.readInt(); 3103 if (DEBUG) { 3104 Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset)); 3105 } 3106 // The next IFD offset needs to be bigger than 8 3107 // since the first IFD offset is at least 8. 3108 if (nextIfdOffset > 8 && nextIfdOffset < dataInputStream.mLength) { 3109 dataInputStream.seek(nextIfdOffset); 3110 if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { 3111 // Do not overwrite thumbnail IFD data if it alreay exists. 3112 readImageFileDirectory(dataInputStream, IFD_TYPE_THUMBNAIL); 3113 } else if (mAttributes[IFD_TYPE_PREVIEW].isEmpty()) { 3114 readImageFileDirectory(dataInputStream, IFD_TYPE_PREVIEW); 3115 } 3116 } 3117 } 3118 } 3119 3120 /** 3121 * JPEG compressed images do not contain IMAGE_LENGTH & IMAGE_WIDTH tags. 3122 * This value uses JpegInterchangeFormat(JPEG data offset) value, and calls getJpegAttributes() 3123 * to locate SOF(Start of Frame) marker and update the image length & width values. 3124 * See JEITA CP-3451C Table 5 and Section 4.8.1. B. 3125 */ 3126 private void retrieveJpegImageSize(ByteOrderedDataInputStream in, int imageType) 3127 throws IOException { 3128 // Check if image already has IMAGE_LENGTH & IMAGE_WIDTH values 3129 ExifAttribute imageLengthAttribute = 3130 (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_LENGTH); 3131 ExifAttribute imageWidthAttribute = 3132 (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_WIDTH); 3133 3134 if (imageLengthAttribute == null || imageWidthAttribute == null) { 3135 // Find if offset for JPEG data exists 3136 ExifAttribute jpegInterchangeFormatAttribute = 3137 (ExifAttribute) mAttributes[imageType].get(TAG_JPEG_INTERCHANGE_FORMAT); 3138 if (jpegInterchangeFormatAttribute != null) { 3139 int jpegInterchangeFormat = 3140 jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder); 3141 3142 // Searches for SOF marker in JPEG data and updates IMAGE_LENGTH & IMAGE_WIDTH tags 3143 getJpegAttributes(in, jpegInterchangeFormat, imageType); 3144 } 3145 } 3146 } 3147 3148 // Sets thumbnail offset & length attributes based on JpegInterchangeFormat or StripOffsets tags 3149 private void setThumbnailData(ByteOrderedDataInputStream in) throws IOException { 3150 HashMap thumbnailData = mAttributes[IFD_TYPE_THUMBNAIL]; 3151 3152 ExifAttribute compressionAttribute = 3153 (ExifAttribute) thumbnailData.get(TAG_COMPRESSION); 3154 if (compressionAttribute != null) { 3155 mThumbnailCompression = compressionAttribute.getIntValue(mExifByteOrder); 3156 switch (mThumbnailCompression) { 3157 case DATA_JPEG: { 3158 handleThumbnailFromJfif(in, thumbnailData); 3159 break; 3160 } 3161 case DATA_UNCOMPRESSED: 3162 case DATA_JPEG_COMPRESSED: { 3163 if (isSupportedDataType(thumbnailData)) { 3164 handleThumbnailFromStrips(in, thumbnailData); 3165 } 3166 break; 3167 } 3168 } 3169 } else { 3170 // Thumbnail data may not contain Compression tag value 3171 handleThumbnailFromJfif(in, thumbnailData); 3172 } 3173 } 3174 3175 // Check JpegInterchangeFormat(JFIF) tags to retrieve thumbnail offset & length values 3176 // and reads the corresponding bytes if stream does not support seek function 3177 private void handleThumbnailFromJfif(ByteOrderedDataInputStream in, HashMap thumbnailData) 3178 throws IOException { 3179 ExifAttribute jpegInterchangeFormatAttribute = 3180 (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT); 3181 ExifAttribute jpegInterchangeFormatLengthAttribute = 3182 (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH); 3183 if (jpegInterchangeFormatAttribute != null 3184 && jpegInterchangeFormatLengthAttribute != null) { 3185 int thumbnailOffset = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder); 3186 int thumbnailLength = jpegInterchangeFormatLengthAttribute.getIntValue(mExifByteOrder); 3187 3188 // The following code limits the size of thumbnail size not to overflow EXIF data area. 3189 thumbnailLength = Math.min(thumbnailLength, in.available() - thumbnailOffset); 3190 if (mMimeType == IMAGE_TYPE_JPEG || mMimeType == IMAGE_TYPE_RAF 3191 || mMimeType == IMAGE_TYPE_RW2) { 3192 thumbnailOffset += mExifOffset; 3193 } else if (mMimeType == IMAGE_TYPE_ORF) { 3194 // Update offset value since RAF files have IFD data preceding MakerNote data. 3195 thumbnailOffset += mOrfMakerNoteOffset; 3196 } 3197 if (DEBUG) { 3198 Log.d(TAG, "Setting thumbnail attributes with offset: " + thumbnailOffset 3199 + ", length: " + thumbnailLength); 3200 } 3201 if (thumbnailOffset > 0 && thumbnailLength > 0) { 3202 mHasThumbnail = true; 3203 mThumbnailOffset = thumbnailOffset; 3204 mThumbnailLength = thumbnailLength; 3205 mThumbnailCompression = DATA_JPEG; 3206 3207 if (mFilename == null && mAssetInputStream == null 3208 && mSeekableFileDescriptor == null) { 3209 // Save the thumbnail in memory if the input doesn't support reading again. 3210 byte[] thumbnailBytes = new byte[thumbnailLength]; 3211 in.seek(thumbnailOffset); 3212 in.readFully(thumbnailBytes); 3213 mThumbnailBytes = thumbnailBytes; 3214 } 3215 } 3216 } 3217 } 3218 3219 // Check StripOffsets & StripByteCounts tags to retrieve thumbnail offset & length values 3220 private void handleThumbnailFromStrips(ByteOrderedDataInputStream in, HashMap thumbnailData) 3221 throws IOException { 3222 ExifAttribute stripOffsetsAttribute = 3223 (ExifAttribute) thumbnailData.get(TAG_STRIP_OFFSETS); 3224 ExifAttribute stripByteCountsAttribute = 3225 (ExifAttribute) thumbnailData.get(TAG_STRIP_BYTE_COUNTS); 3226 3227 if (stripOffsetsAttribute != null && stripByteCountsAttribute != null) { 3228 long[] stripOffsets = 3229 convertToLongArray(stripOffsetsAttribute.getValue(mExifByteOrder)); 3230 long[] stripByteCounts = 3231 convertToLongArray(stripByteCountsAttribute.getValue(mExifByteOrder)); 3232 3233 if (stripOffsets == null) { 3234 Log.w(TAG, "stripOffsets should not be null."); 3235 return; 3236 } 3237 if (stripByteCounts == null) { 3238 Log.w(TAG, "stripByteCounts should not be null."); 3239 return; 3240 } 3241 3242 // Set thumbnail byte array data for non-consecutive strip bytes 3243 byte[] totalStripBytes = 3244 new byte[(int) Arrays.stream(stripByteCounts).sum()]; 3245 3246 int bytesRead = 0; 3247 int bytesAdded = 0; 3248 for (int i = 0; i < stripOffsets.length; i++) { 3249 int stripOffset = (int) stripOffsets[i]; 3250 int stripByteCount = (int) stripByteCounts[i]; 3251 3252 // Skip to offset 3253 int skipBytes = stripOffset - bytesRead; 3254 if (skipBytes < 0) { 3255 Log.d(TAG, "Invalid strip offset value"); 3256 } 3257 in.seek(skipBytes); 3258 bytesRead += skipBytes; 3259 3260 // Read strip bytes 3261 byte[] stripBytes = new byte[stripByteCount]; 3262 in.read(stripBytes); 3263 bytesRead += stripByteCount; 3264 3265 // Add bytes to array 3266 System.arraycopy(stripBytes, 0, totalStripBytes, bytesAdded, 3267 stripBytes.length); 3268 bytesAdded += stripBytes.length; 3269 } 3270 3271 mHasThumbnail = true; 3272 mThumbnailBytes = totalStripBytes; 3273 mThumbnailLength = totalStripBytes.length; 3274 } 3275 } 3276 3277 // Check if thumbnail data type is currently supported or not 3278 private boolean isSupportedDataType(HashMap thumbnailData) throws IOException { 3279 ExifAttribute bitsPerSampleAttribute = 3280 (ExifAttribute) thumbnailData.get(TAG_BITS_PER_SAMPLE); 3281 if (bitsPerSampleAttribute != null) { 3282 int[] bitsPerSampleValue = (int[]) bitsPerSampleAttribute.getValue(mExifByteOrder); 3283 3284 if (Arrays.equals(BITS_PER_SAMPLE_RGB, bitsPerSampleValue)) { 3285 return true; 3286 } 3287 3288 // See DNG Specification 1.4.0.0. Section 3, Compression. 3289 if (mMimeType == IMAGE_TYPE_DNG) { 3290 ExifAttribute photometricInterpretationAttribute = 3291 (ExifAttribute) thumbnailData.get(TAG_PHOTOMETRIC_INTERPRETATION); 3292 if (photometricInterpretationAttribute != null) { 3293 int photometricInterpretationValue 3294 = photometricInterpretationAttribute.getIntValue(mExifByteOrder); 3295 if ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO 3296 && Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_GREYSCALE_2)) 3297 || ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_YCBCR) 3298 && (Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_RGB)))) { 3299 return true; 3300 } else { 3301 // TODO: Add support for lossless Huffman JPEG data 3302 } 3303 } 3304 } 3305 } 3306 if (DEBUG) { 3307 Log.d(TAG, "Unsupported data type value"); 3308 } 3309 return false; 3310 } 3311 3312 // Returns true if the image length and width values are <= 512. 3313 // See Section 4.8 of http://standardsproposals.bsigroup.com/Home/getPDF/567 3314 private boolean isThumbnail(HashMap map) throws IOException { 3315 ExifAttribute imageLengthAttribute = (ExifAttribute) map.get(TAG_IMAGE_LENGTH); 3316 ExifAttribute imageWidthAttribute = (ExifAttribute) map.get(TAG_IMAGE_WIDTH); 3317 3318 if (imageLengthAttribute != null && imageWidthAttribute != null) { 3319 int imageLengthValue = imageLengthAttribute.getIntValue(mExifByteOrder); 3320 int imageWidthValue = imageWidthAttribute.getIntValue(mExifByteOrder); 3321 if (imageLengthValue <= MAX_THUMBNAIL_SIZE && imageWidthValue <= MAX_THUMBNAIL_SIZE) { 3322 return true; 3323 } 3324 } 3325 return false; 3326 } 3327 3328 // Validate primary, preview, thumbnail image data by comparing image size 3329 private void validateImages(InputStream in) throws IOException { 3330 // Swap images based on size (primary > preview > thumbnail) 3331 swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_PREVIEW); 3332 swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_THUMBNAIL); 3333 swapBasedOnImageSize(IFD_TYPE_PREVIEW, IFD_TYPE_THUMBNAIL); 3334 3335 // Check if image has PixelXDimension/PixelYDimension tags, which contain valid image 3336 // sizes, excluding padding at the right end or bottom end of the image to make sure that 3337 // the values are multiples of 64. See JEITA CP-3451C Table 5 and Section 4.8.1. B. 3338 ExifAttribute pixelXDimAttribute = 3339 (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_X_DIMENSION); 3340 ExifAttribute pixelYDimAttribute = 3341 (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_Y_DIMENSION); 3342 if (pixelXDimAttribute != null && pixelYDimAttribute != null) { 3343 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, pixelXDimAttribute); 3344 mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, pixelYDimAttribute); 3345 } 3346 3347 // Check whether thumbnail image exists and whether preview image satisfies the thumbnail 3348 // image requirements 3349 if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { 3350 if (isThumbnail(mAttributes[IFD_TYPE_PREVIEW])) { 3351 mAttributes[IFD_TYPE_THUMBNAIL] = mAttributes[IFD_TYPE_PREVIEW]; 3352 mAttributes[IFD_TYPE_PREVIEW] = new HashMap(); 3353 } 3354 } 3355 3356 // Check if the thumbnail image satisfies the thumbnail size requirements 3357 if (!isThumbnail(mAttributes[IFD_TYPE_THUMBNAIL])) { 3358 Log.d(TAG, "No image meets the size requirements of a thumbnail image."); 3359 } 3360 } 3361 3362 /** 3363 * If image is uncompressed, ImageWidth/Length tags are used to store size info. 3364 * However, uncompressed images often store extra pixels around the edges of the final image, 3365 * which results in larger values for TAG_IMAGE_WIDTH and TAG_IMAGE_LENGTH tags. 3366 * This method corrects those tag values by checking first the values of TAG_DEFAULT_CROP_SIZE 3367 * See DNG Specification 1.4.0.0. Section 4. (DefaultCropSize) 3368 * 3369 * If image is a RW2 file, valid image sizes are stored in SensorBorder tags. 3370 * See tiff_parser.cc GetFullDimension32() 3371 * */ 3372 private void updateImageSizeValues(ByteOrderedDataInputStream in, int imageType) 3373 throws IOException { 3374 // Uncompressed image valid image size values 3375 ExifAttribute defaultCropSizeAttribute = 3376 (ExifAttribute) mAttributes[imageType].get(TAG_DEFAULT_CROP_SIZE); 3377 // RW2 image valid image size values 3378 ExifAttribute topBorderAttribute = 3379 (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_TOP_BORDER); 3380 ExifAttribute leftBorderAttribute = 3381 (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_LEFT_BORDER); 3382 ExifAttribute bottomBorderAttribute = 3383 (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_BOTTOM_BORDER); 3384 ExifAttribute rightBorderAttribute = 3385 (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_RIGHT_BORDER); 3386 3387 if (defaultCropSizeAttribute != null) { 3388 // Update for uncompressed image 3389 ExifAttribute defaultCropSizeXAttribute, defaultCropSizeYAttribute; 3390 if (defaultCropSizeAttribute.format == IFD_FORMAT_URATIONAL) { 3391 Rational[] defaultCropSizeValue = 3392 (Rational[]) defaultCropSizeAttribute.getValue(mExifByteOrder); 3393 defaultCropSizeXAttribute = 3394 ExifAttribute.createURational(defaultCropSizeValue[0], mExifByteOrder); 3395 defaultCropSizeYAttribute = 3396 ExifAttribute.createURational(defaultCropSizeValue[1], mExifByteOrder); 3397 } else { 3398 int[] defaultCropSizeValue = 3399 (int[]) defaultCropSizeAttribute.getValue(mExifByteOrder); 3400 defaultCropSizeXAttribute = 3401 ExifAttribute.createUShort(defaultCropSizeValue[0], mExifByteOrder); 3402 defaultCropSizeYAttribute = 3403 ExifAttribute.createUShort(defaultCropSizeValue[1], mExifByteOrder); 3404 } 3405 mAttributes[imageType].put(TAG_IMAGE_WIDTH, defaultCropSizeXAttribute); 3406 mAttributes[imageType].put(TAG_IMAGE_LENGTH, defaultCropSizeYAttribute); 3407 } else if (topBorderAttribute != null && leftBorderAttribute != null && 3408 bottomBorderAttribute != null && rightBorderAttribute != null) { 3409 // Update for RW2 image 3410 int topBorderValue = topBorderAttribute.getIntValue(mExifByteOrder); 3411 int bottomBorderValue = bottomBorderAttribute.getIntValue(mExifByteOrder); 3412 int rightBorderValue = rightBorderAttribute.getIntValue(mExifByteOrder); 3413 int leftBorderValue = leftBorderAttribute.getIntValue(mExifByteOrder); 3414 if (bottomBorderValue > topBorderValue && rightBorderValue > leftBorderValue) { 3415 int length = bottomBorderValue - topBorderValue; 3416 int width = rightBorderValue - leftBorderValue; 3417 ExifAttribute imageLengthAttribute = 3418 ExifAttribute.createUShort(length, mExifByteOrder); 3419 ExifAttribute imageWidthAttribute = 3420 ExifAttribute.createUShort(width, mExifByteOrder); 3421 mAttributes[imageType].put(TAG_IMAGE_LENGTH, imageLengthAttribute); 3422 mAttributes[imageType].put(TAG_IMAGE_WIDTH, imageWidthAttribute); 3423 } 3424 } else { 3425 retrieveJpegImageSize(in, imageType); 3426 } 3427 } 3428 3429 // Writes an Exif segment into the given output stream. 3430 private int writeExifSegment(ByteOrderedDataOutputStream dataOutputStream, 3431 int exifOffsetFromBeginning) throws IOException { 3432 // The following variables are for calculating each IFD tag group size in bytes. 3433 int[] ifdOffsets = new int[EXIF_TAGS.length]; 3434 int[] ifdDataSizes = new int[EXIF_TAGS.length]; 3435 3436 // Remove IFD pointer tags (we'll re-add it later.) 3437 for (ExifTag tag : EXIF_POINTER_TAGS) { 3438 removeAttribute(tag.name); 3439 } 3440 // Remove old thumbnail data 3441 removeAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name); 3442 removeAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name); 3443 3444 // Remove null value tags. 3445 for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { 3446 for (Object obj : mAttributes[ifdType].entrySet().toArray()) { 3447 final Map.Entry entry = (Map.Entry) obj; 3448 if (entry.getValue() == null) { 3449 mAttributes[ifdType].remove(entry.getKey()); 3450 } 3451 } 3452 } 3453 3454 // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD 3455 // offset when there is one or more tags in the thumbnail IFD. 3456 if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) { 3457 mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name, 3458 ExifAttribute.createULong(0, mExifByteOrder)); 3459 } 3460 if (!mAttributes[IFD_TYPE_GPS].isEmpty()) { 3461 mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name, 3462 ExifAttribute.createULong(0, mExifByteOrder)); 3463 } 3464 if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) { 3465 mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, 3466 ExifAttribute.createULong(0, mExifByteOrder)); 3467 } 3468 if (mHasThumbnail) { 3469 mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name, 3470 ExifAttribute.createULong(0, mExifByteOrder)); 3471 mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, 3472 ExifAttribute.createULong(mThumbnailLength, mExifByteOrder)); 3473 } 3474 3475 // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry 3476 // value which has a bigger size than 4 bytes. 3477 for (int i = 0; i < EXIF_TAGS.length; ++i) { 3478 int sum = 0; 3479 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) { 3480 final ExifAttribute exifAttribute = (ExifAttribute) entry.getValue(); 3481 final int size = exifAttribute.size(); 3482 if (size > 4) { 3483 sum += size; 3484 } 3485 } 3486 ifdDataSizes[i] += sum; 3487 } 3488 3489 // Calculate IFD offsets. 3490 int position = 8; 3491 for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { 3492 if (!mAttributes[ifdType].isEmpty()) { 3493 ifdOffsets[ifdType] = position; 3494 position += 2 + mAttributes[ifdType].size() * 12 + 4 + ifdDataSizes[ifdType]; 3495 } 3496 } 3497 if (mHasThumbnail) { 3498 int thumbnailOffset = position; 3499 mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name, 3500 ExifAttribute.createULong(thumbnailOffset, mExifByteOrder)); 3501 mThumbnailOffset = exifOffsetFromBeginning + thumbnailOffset; 3502 position += mThumbnailLength; 3503 } 3504 3505 // Calculate the total size 3506 int totalSize = position + 8; // eight bytes is for header part. 3507 if (DEBUG) { 3508 Log.d(TAG, "totalSize length: " + totalSize); 3509 for (int i = 0; i < EXIF_TAGS.length; ++i) { 3510 Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d", 3511 i, ifdOffsets[i], mAttributes[i].size(), ifdDataSizes[i])); 3512 } 3513 } 3514 3515 // Update IFD pointer tags with the calculated offsets. 3516 if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) { 3517 mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name, 3518 ExifAttribute.createULong(ifdOffsets[IFD_TYPE_EXIF], mExifByteOrder)); 3519 } 3520 if (!mAttributes[IFD_TYPE_GPS].isEmpty()) { 3521 mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name, 3522 ExifAttribute.createULong(ifdOffsets[IFD_TYPE_GPS], mExifByteOrder)); 3523 } 3524 if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) { 3525 mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, ExifAttribute.createULong( 3526 ifdOffsets[IFD_TYPE_INTEROPERABILITY], mExifByteOrder)); 3527 } 3528 3529 // Write TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. 3530 dataOutputStream.writeUnsignedShort(totalSize); 3531 dataOutputStream.write(IDENTIFIER_EXIF_APP1); 3532 dataOutputStream.writeShort(mExifByteOrder == ByteOrder.BIG_ENDIAN 3533 ? BYTE_ALIGN_MM : BYTE_ALIGN_II); 3534 dataOutputStream.setByteOrder(mExifByteOrder); 3535 dataOutputStream.writeUnsignedShort(START_CODE); 3536 dataOutputStream.writeUnsignedInt(IFD_OFFSET); 3537 3538 // Write IFD groups. See JEITA CP-3451C Section 4.5.8. Figure 9. 3539 for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { 3540 if (!mAttributes[ifdType].isEmpty()) { 3541 // See JEITA CP-3451C Section 4.6.2: IFD structure. 3542 // Write entry count 3543 dataOutputStream.writeUnsignedShort(mAttributes[ifdType].size()); 3544 3545 // Write entry info 3546 int dataOffset = ifdOffsets[ifdType] + 2 + mAttributes[ifdType].size() * 12 + 4; 3547 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[ifdType].entrySet()) { 3548 // Convert tag name to tag number. 3549 final ExifTag tag = 3550 (ExifTag) sExifTagMapsForWriting[ifdType].get(entry.getKey()); 3551 final int tagNumber = tag.number; 3552 final ExifAttribute attribute = (ExifAttribute) entry.getValue(); 3553 final int size = attribute.size(); 3554 3555 dataOutputStream.writeUnsignedShort(tagNumber); 3556 dataOutputStream.writeUnsignedShort(attribute.format); 3557 dataOutputStream.writeInt(attribute.numberOfComponents); 3558 if (size > 4) { 3559 dataOutputStream.writeUnsignedInt(dataOffset); 3560 dataOffset += size; 3561 } else { 3562 dataOutputStream.write(attribute.bytes); 3563 // Fill zero up to 4 bytes 3564 if (size < 4) { 3565 for (int i = size; i < 4; ++i) { 3566 dataOutputStream.writeByte(0); 3567 } 3568 } 3569 } 3570 } 3571 3572 // Write the next offset. It writes the offset of thumbnail IFD if there is one or 3573 // more tags in the thumbnail IFD when the current IFD is the primary image TIFF 3574 // IFD; Otherwise 0. 3575 if (ifdType == 0 && !mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { 3576 dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_TYPE_THUMBNAIL]); 3577 } else { 3578 dataOutputStream.writeUnsignedInt(0); 3579 } 3580 3581 // Write values of data field exceeding 4 bytes after the next offset. 3582 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[ifdType].entrySet()) { 3583 ExifAttribute attribute = (ExifAttribute) entry.getValue(); 3584 3585 if (attribute.bytes.length > 4) { 3586 dataOutputStream.write(attribute.bytes, 0, attribute.bytes.length); 3587 } 3588 } 3589 } 3590 } 3591 3592 // Write thumbnail 3593 if (mHasThumbnail) { 3594 dataOutputStream.write(getThumbnailBytes()); 3595 } 3596 3597 // Reset the byte order to big endian in order to write remaining parts of the JPEG file. 3598 dataOutputStream.setByteOrder(ByteOrder.BIG_ENDIAN); 3599 3600 return totalSize; 3601 } 3602 3603 /** 3604 * Determines the data format of EXIF entry value. 3605 * 3606 * @param entryValue The value to be determined. 3607 * @return Returns two data formats gussed as a pair in integer. If there is no two candidate 3608 data formats for the given entry value, returns {@code -1} in the second of the pair. 3609 */ 3610 private static Pair<Integer, Integer> guessDataFormat(String entryValue) { 3611 // See TIFF 6.0 Section 2, "Image File Directory". 3612 // Take the first component if there are more than one component. 3613 if (entryValue.contains(",")) { 3614 String[] entryValues = entryValue.split(","); 3615 Pair<Integer, Integer> dataFormat = guessDataFormat(entryValues[0]); 3616 if (dataFormat.first == IFD_FORMAT_STRING) { 3617 return dataFormat; 3618 } 3619 for (int i = 1; i < entryValues.length; ++i) { 3620 final Pair<Integer, Integer> guessDataFormat = guessDataFormat(entryValues[i]); 3621 int first = -1, second = -1; 3622 if (guessDataFormat.first == dataFormat.first 3623 || guessDataFormat.second == dataFormat.first) { 3624 first = dataFormat.first; 3625 } 3626 if (dataFormat.second != -1 && (guessDataFormat.first == dataFormat.second 3627 || guessDataFormat.second == dataFormat.second)) { 3628 second = dataFormat.second; 3629 } 3630 if (first == -1 && second == -1) { 3631 return new Pair<>(IFD_FORMAT_STRING, -1); 3632 } 3633 if (first == -1) { 3634 dataFormat = new Pair<>(second, -1); 3635 continue; 3636 } 3637 if (second == -1) { 3638 dataFormat = new Pair<>(first, -1); 3639 continue; 3640 } 3641 } 3642 return dataFormat; 3643 } 3644 3645 if (entryValue.contains("/")) { 3646 String[] rationalNumber = entryValue.split("/"); 3647 if (rationalNumber.length == 2) { 3648 try { 3649 long numerator = (long) Double.parseDouble(rationalNumber[0]); 3650 long denominator = (long) Double.parseDouble(rationalNumber[1]); 3651 if (numerator < 0L || denominator < 0L) { 3652 return new Pair<>(IFD_FORMAT_SRATIONAL, -1); 3653 } 3654 if (numerator > Integer.MAX_VALUE || denominator > Integer.MAX_VALUE) { 3655 return new Pair<>(IFD_FORMAT_URATIONAL, -1); 3656 } 3657 return new Pair<>(IFD_FORMAT_SRATIONAL, IFD_FORMAT_URATIONAL); 3658 } catch (NumberFormatException e) { 3659 // Ignored 3660 } 3661 } 3662 return new Pair<>(IFD_FORMAT_STRING, -1); 3663 } 3664 try { 3665 Long longValue = Long.parseLong(entryValue); 3666 if (longValue >= 0 && longValue <= 65535) { 3667 return new Pair<>(IFD_FORMAT_USHORT, IFD_FORMAT_ULONG); 3668 } 3669 if (longValue < 0) { 3670 return new Pair<>(IFD_FORMAT_SLONG, -1); 3671 } 3672 return new Pair<>(IFD_FORMAT_ULONG, -1); 3673 } catch (NumberFormatException e) { 3674 // Ignored 3675 } 3676 try { 3677 Double.parseDouble(entryValue); 3678 return new Pair<>(IFD_FORMAT_DOUBLE, -1); 3679 } catch (NumberFormatException e) { 3680 // Ignored 3681 } 3682 return new Pair<>(IFD_FORMAT_STRING, -1); 3683 } 3684 3685 // An input stream to parse EXIF data area, which can be written in either little or big endian 3686 // order. 3687 private static class ByteOrderedDataInputStream extends InputStream implements DataInput { 3688 private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; 3689 private static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; 3690 3691 private DataInputStream mDataInputStream; 3692 private InputStream mInputStream; 3693 private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN; 3694 private final int mLength; 3695 private int mPosition; 3696 3697 public ByteOrderedDataInputStream(InputStream in) throws IOException { 3698 mInputStream = in; 3699 mDataInputStream = new DataInputStream(in); 3700 mLength = mDataInputStream.available(); 3701 mPosition = 0; 3702 mDataInputStream.mark(mLength); 3703 } 3704 3705 public ByteOrderedDataInputStream(byte[] bytes) throws IOException { 3706 this(new ByteArrayInputStream(bytes)); 3707 } 3708 3709 public void setByteOrder(ByteOrder byteOrder) { 3710 mByteOrder = byteOrder; 3711 } 3712 3713 public void seek(long byteCount) throws IOException { 3714 if (mPosition > byteCount) { 3715 mPosition = 0; 3716 mDataInputStream.reset(); 3717 mDataInputStream.mark(mLength); 3718 } else { 3719 byteCount -= mPosition; 3720 } 3721 3722 if (skipBytes((int) byteCount) != (int) byteCount) { 3723 throw new IOException("Couldn't seek up to the byteCount"); 3724 } 3725 } 3726 3727 public int peek() { 3728 return mPosition; 3729 } 3730 3731 @Override 3732 public int available() throws IOException { 3733 return mDataInputStream.available(); 3734 } 3735 3736 @Override 3737 public int read() throws IOException { 3738 ++mPosition; 3739 return mDataInputStream.read(); 3740 } 3741 3742 @Override 3743 public int readUnsignedByte() throws IOException { 3744 ++mPosition; 3745 return mDataInputStream.readUnsignedByte(); 3746 } 3747 3748 @Override 3749 public String readLine() throws IOException { 3750 Log.d(TAG, "Currently unsupported"); 3751 return null; 3752 } 3753 3754 @Override 3755 public boolean readBoolean() throws IOException { 3756 ++mPosition; 3757 return mDataInputStream.readBoolean(); 3758 } 3759 3760 @Override 3761 public char readChar() throws IOException { 3762 mPosition += 2; 3763 return mDataInputStream.readChar(); 3764 } 3765 3766 @Override 3767 public String readUTF() throws IOException { 3768 mPosition += 2; 3769 return mDataInputStream.readUTF(); 3770 } 3771 3772 @Override 3773 public void readFully(byte[] buffer, int offset, int length) throws IOException { 3774 mPosition += length; 3775 if (mPosition > mLength) { 3776 throw new EOFException(); 3777 } 3778 if (mDataInputStream.read(buffer, offset, length) != length) { 3779 throw new IOException("Couldn't read up to the length of buffer"); 3780 } 3781 } 3782 3783 @Override 3784 public void readFully(byte[] buffer) throws IOException { 3785 mPosition += buffer.length; 3786 if (mPosition > mLength) { 3787 throw new EOFException(); 3788 } 3789 if (mDataInputStream.read(buffer, 0, buffer.length) != buffer.length) { 3790 throw new IOException("Couldn't read up to the length of buffer"); 3791 } 3792 } 3793 3794 @Override 3795 public byte readByte() throws IOException { 3796 ++mPosition; 3797 if (mPosition > mLength) { 3798 throw new EOFException(); 3799 } 3800 int ch = mDataInputStream.read(); 3801 if (ch < 0) { 3802 throw new EOFException(); 3803 } 3804 return (byte) ch; 3805 } 3806 3807 @Override 3808 public short readShort() throws IOException { 3809 mPosition += 2; 3810 if (mPosition > mLength) { 3811 throw new EOFException(); 3812 } 3813 int ch1 = mDataInputStream.read(); 3814 int ch2 = mDataInputStream.read(); 3815 if ((ch1 | ch2) < 0) { 3816 throw new EOFException(); 3817 } 3818 if (mByteOrder == LITTLE_ENDIAN) { 3819 return (short) ((ch2 << 8) + (ch1)); 3820 } else if (mByteOrder == BIG_ENDIAN) { 3821 return (short) ((ch1 << 8) + (ch2)); 3822 } 3823 throw new IOException("Invalid byte order: " + mByteOrder); 3824 } 3825 3826 @Override 3827 public int readInt() throws IOException { 3828 mPosition += 4; 3829 if (mPosition > mLength) { 3830 throw new EOFException(); 3831 } 3832 int ch1 = mDataInputStream.read(); 3833 int ch2 = mDataInputStream.read(); 3834 int ch3 = mDataInputStream.read(); 3835 int ch4 = mDataInputStream.read(); 3836 if ((ch1 | ch2 | ch3 | ch4) < 0) { 3837 throw new EOFException(); 3838 } 3839 if (mByteOrder == LITTLE_ENDIAN) { 3840 return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1); 3841 } else if (mByteOrder == BIG_ENDIAN) { 3842 return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4); 3843 } 3844 throw new IOException("Invalid byte order: " + mByteOrder); 3845 } 3846 3847 @Override 3848 public int skipBytes(int byteCount) throws IOException { 3849 int totalSkip = Math.min(byteCount, mLength - mPosition); 3850 int skipped = 0; 3851 while (skipped < totalSkip) { 3852 skipped += mDataInputStream.skipBytes(totalSkip - skipped); 3853 } 3854 mPosition += skipped; 3855 return skipped; 3856 } 3857 3858 public int readUnsignedShort() throws IOException { 3859 mPosition += 2; 3860 if (mPosition > mLength) { 3861 throw new EOFException(); 3862 } 3863 int ch1 = mDataInputStream.read(); 3864 int ch2 = mDataInputStream.read(); 3865 if ((ch1 | ch2) < 0) { 3866 throw new EOFException(); 3867 } 3868 if (mByteOrder == LITTLE_ENDIAN) { 3869 return ((ch2 << 8) + (ch1)); 3870 } else if (mByteOrder == BIG_ENDIAN) { 3871 return ((ch1 << 8) + (ch2)); 3872 } 3873 throw new IOException("Invalid byte order: " + mByteOrder); 3874 } 3875 3876 public long readUnsignedInt() throws IOException { 3877 return readInt() & 0xffffffffL; 3878 } 3879 3880 @Override 3881 public long readLong() throws IOException { 3882 mPosition += 8; 3883 if (mPosition > mLength) { 3884 throw new EOFException(); 3885 } 3886 int ch1 = mDataInputStream.read(); 3887 int ch2 = mDataInputStream.read(); 3888 int ch3 = mDataInputStream.read(); 3889 int ch4 = mDataInputStream.read(); 3890 int ch5 = mDataInputStream.read(); 3891 int ch6 = mDataInputStream.read(); 3892 int ch7 = mDataInputStream.read(); 3893 int ch8 = mDataInputStream.read(); 3894 if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) { 3895 throw new EOFException(); 3896 } 3897 if (mByteOrder == LITTLE_ENDIAN) { 3898 return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40) 3899 + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16) 3900 + ((long) ch2 << 8) + (long) ch1); 3901 } else if (mByteOrder == BIG_ENDIAN) { 3902 return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40) 3903 + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16) 3904 + ((long) ch7 << 8) + (long) ch8); 3905 } 3906 throw new IOException("Invalid byte order: " + mByteOrder); 3907 } 3908 3909 @Override 3910 public float readFloat() throws IOException { 3911 return Float.intBitsToFloat(readInt()); 3912 } 3913 3914 @Override 3915 public double readDouble() throws IOException { 3916 return Double.longBitsToDouble(readLong()); 3917 } 3918 } 3919 3920 // An output stream to write EXIF data area, which can be written in either little or big endian 3921 // order. 3922 private static class ByteOrderedDataOutputStream extends FilterOutputStream { 3923 private final OutputStream mOutputStream; 3924 private ByteOrder mByteOrder; 3925 3926 public ByteOrderedDataOutputStream(OutputStream out, ByteOrder byteOrder) { 3927 super(out); 3928 mOutputStream = out; 3929 mByteOrder = byteOrder; 3930 } 3931 3932 public void setByteOrder(ByteOrder byteOrder) { 3933 mByteOrder = byteOrder; 3934 } 3935 3936 public void write(byte[] bytes) throws IOException { 3937 mOutputStream.write(bytes); 3938 } 3939 3940 public void write(byte[] bytes, int offset, int length) throws IOException { 3941 mOutputStream.write(bytes, offset, length); 3942 } 3943 3944 public void writeByte(int val) throws IOException { 3945 mOutputStream.write(val); 3946 } 3947 3948 public void writeShort(short val) throws IOException { 3949 if (mByteOrder == ByteOrder.LITTLE_ENDIAN) { 3950 mOutputStream.write((val >>> 0) & 0xFF); 3951 mOutputStream.write((val >>> 8) & 0xFF); 3952 } else if (mByteOrder == ByteOrder.BIG_ENDIAN) { 3953 mOutputStream.write((val >>> 8) & 0xFF); 3954 mOutputStream.write((val >>> 0) & 0xFF); 3955 } 3956 } 3957 3958 public void writeInt(int val) throws IOException { 3959 if (mByteOrder == ByteOrder.LITTLE_ENDIAN) { 3960 mOutputStream.write((val >>> 0) & 0xFF); 3961 mOutputStream.write((val >>> 8) & 0xFF); 3962 mOutputStream.write((val >>> 16) & 0xFF); 3963 mOutputStream.write((val >>> 24) & 0xFF); 3964 } else if (mByteOrder == ByteOrder.BIG_ENDIAN) { 3965 mOutputStream.write((val >>> 24) & 0xFF); 3966 mOutputStream.write((val >>> 16) & 0xFF); 3967 mOutputStream.write((val >>> 8) & 0xFF); 3968 mOutputStream.write((val >>> 0) & 0xFF); 3969 } 3970 } 3971 3972 public void writeUnsignedShort(int val) throws IOException { 3973 writeShort((short) val); 3974 } 3975 3976 public void writeUnsignedInt(long val) throws IOException { 3977 writeInt((int) val); 3978 } 3979 } 3980 3981 // Swaps image data based on image size 3982 private void swapBasedOnImageSize(@IfdType int firstIfdType, @IfdType int secondIfdType) 3983 throws IOException { 3984 if (mAttributes[firstIfdType].isEmpty() || mAttributes[secondIfdType].isEmpty()) { 3985 if (DEBUG) { 3986 Log.d(TAG, "Cannot perform swap since only one image data exists"); 3987 } 3988 return; 3989 } 3990 3991 ExifAttribute firstImageLengthAttribute = 3992 (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_LENGTH); 3993 ExifAttribute firstImageWidthAttribute = 3994 (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_WIDTH); 3995 ExifAttribute secondImageLengthAttribute = 3996 (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_LENGTH); 3997 ExifAttribute secondImageWidthAttribute = 3998 (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_WIDTH); 3999 4000 if (firstImageLengthAttribute == null || firstImageWidthAttribute == null) { 4001 if (DEBUG) { 4002 Log.d(TAG, "First image does not contain valid size information"); 4003 } 4004 } else if (secondImageLengthAttribute == null || secondImageWidthAttribute == null) { 4005 if (DEBUG) { 4006 Log.d(TAG, "Second image does not contain valid size information"); 4007 } 4008 } else { 4009 int firstImageLengthValue = firstImageLengthAttribute.getIntValue(mExifByteOrder); 4010 int firstImageWidthValue = firstImageWidthAttribute.getIntValue(mExifByteOrder); 4011 int secondImageLengthValue = secondImageLengthAttribute.getIntValue(mExifByteOrder); 4012 int secondImageWidthValue = secondImageWidthAttribute.getIntValue(mExifByteOrder); 4013 4014 if (firstImageLengthValue < secondImageLengthValue && 4015 firstImageWidthValue < secondImageWidthValue) { 4016 HashMap tempMap = mAttributes[firstIfdType]; 4017 mAttributes[firstIfdType] = mAttributes[secondIfdType]; 4018 mAttributes[secondIfdType] = tempMap; 4019 } 4020 } 4021 } 4022 4023 // Checks if there is a match 4024 private boolean containsMatch(byte[] mainBytes, byte[] findBytes) { 4025 for (int i = 0; i < mainBytes.length - findBytes.length; i++) { 4026 for (int j = 0; j < findBytes.length; j++) { 4027 if (mainBytes[i + j] != findBytes[j]) { 4028 break; 4029 } 4030 if (j == findBytes.length - 1) { 4031 return true; 4032 } 4033 } 4034 } 4035 return false; 4036 } 4037 4038 /** 4039 * Convert given int[] to long[]. If long[] is given, just return it. 4040 * Return null for other types of input. 4041 */ 4042 private static long[] convertToLongArray(Object inputObj) { 4043 if (inputObj instanceof int[]) { 4044 int[] input = (int[]) inputObj; 4045 long[] result = new long[input.length]; 4046 for (int i = 0; i < input.length; i++) { 4047 result[i] = input[i]; 4048 } 4049 return result; 4050 } else if (inputObj instanceof long[]) { 4051 return (long[]) inputObj; 4052 } 4053 return null; 4054 } 4055} 4056