ExifInterface.java revision 36a20cdde3176f24279e2382f878cecdbecafa9d
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; 27 28import java.io.BufferedInputStream; 29import java.io.ByteArrayInputStream; 30import java.io.DataInputStream; 31import java.io.DataOutputStream; 32import java.io.EOFException; 33import java.io.File; 34import java.io.FileDescriptor; 35import java.io.FileInputStream; 36import java.io.FileNotFoundException; 37import java.io.FileOutputStream; 38import java.io.IOException; 39import java.io.InputStream; 40import java.io.OutputStream; 41import java.nio.ByteOrder; 42import java.nio.charset.Charset; 43import java.text.ParsePosition; 44import java.text.SimpleDateFormat; 45import java.util.Arrays; 46import java.util.Date; 47import java.util.HashMap; 48import java.util.Map; 49import java.util.Set; 50import java.util.TimeZone; 51import java.util.regex.Pattern; 52 53import libcore.io.IoUtils; 54import libcore.io.Streams; 55 56/** 57 * This is a class for reading and writing Exif tags in a JPEG file or a RAW image file. 58 * <p> 59 * Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF and RAF. 60 * <p> 61 * Attribute mutation is supported for JPEG image files. 62 */ 63public class ExifInterface { 64 private static final String TAG = "ExifInterface"; 65 private static final boolean DEBUG = false; 66 67 // The Exif tag names 68 /** Type is String. */ 69 public static final String TAG_ARTIST = "Artist"; 70 /** Type is int. */ 71 public static final String TAG_BITS_PER_SAMPLE = "BitsPerSample"; 72 /** Type is int. */ 73 public static final String TAG_COMPRESSION = "Compression"; 74 /** Type is String. */ 75 public static final String TAG_COPYRIGHT = "Copyright"; 76 /** Type is String. */ 77 public static final String TAG_DATETIME = "DateTime"; 78 /** Type is String. */ 79 public static final String TAG_IMAGE_DESCRIPTION = "ImageDescription"; 80 /** Type is int. */ 81 public static final String TAG_IMAGE_LENGTH = "ImageLength"; 82 /** Type is int. */ 83 public static final String TAG_IMAGE_WIDTH = "ImageWidth"; 84 /** Type is int. */ 85 public static final String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat"; 86 /** Type is int. */ 87 public static final String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength"; 88 /** Type is String. */ 89 public static final String TAG_MAKE = "Make"; 90 /** Type is String. */ 91 public static final String TAG_MODEL = "Model"; 92 /** Type is int. */ 93 public static final String TAG_ORIENTATION = "Orientation"; 94 /** Type is int. */ 95 public static final String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation"; 96 /** Type is int. */ 97 public static final String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration"; 98 /** Type is rational. */ 99 public static final String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities"; 100 /** Type is rational. */ 101 public static final String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite"; 102 /** Type is int. */ 103 public static final String TAG_RESOLUTION_UNIT = "ResolutionUnit"; 104 /** Type is int. */ 105 public static final String TAG_ROWS_PER_STRIP = "RowsPerStrip"; 106 /** Type is int. */ 107 public static final String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel"; 108 /** Type is String. */ 109 public static final String TAG_SOFTWARE = "Software"; 110 /** Type is int. */ 111 public static final String TAG_STRIP_BYTE_COUNTS = "StripByteCounts"; 112 /** Type is int. */ 113 public static final String TAG_STRIP_OFFSETS = "StripOffsets"; 114 /** Type is int. */ 115 public static final String TAG_TRANSFER_FUNCTION = "TransferFunction"; 116 /** Type is rational. */ 117 public static final String TAG_WHITE_POINT = "WhitePoint"; 118 /** Type is rational. */ 119 public static final String TAG_X_RESOLUTION = "XResolution"; 120 /** Type is rational. */ 121 public static final String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients"; 122 /** Type is int. */ 123 public static final String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning"; 124 /** Type is int. */ 125 public static final String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling"; 126 /** Type is rational. */ 127 public static final String TAG_Y_RESOLUTION = "YResolution"; 128 /** Type is rational. */ 129 public static final String TAG_APERTURE_VALUE = "ApertureValue"; 130 /** Type is rational. */ 131 public static final String TAG_BRIGHTNESS_VALUE = "BrightnessValue"; 132 /** Type is String. */ 133 public static final String TAG_CFA_PATTERN = "CFAPattern"; 134 /** Type is int. */ 135 public static final String TAG_COLOR_SPACE = "ColorSpace"; 136 /** Type is String. */ 137 public static final String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration"; 138 /** Type is rational. */ 139 public static final String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel"; 140 /** Type is int. */ 141 public static final String TAG_CONTRAST = "Contrast"; 142 /** Type is int. */ 143 public static final String TAG_CUSTOM_RENDERED = "CustomRendered"; 144 /** Type is String. */ 145 public static final String TAG_DATETIME_DIGITIZED = "DateTimeDigitized"; 146 /** Type is String. */ 147 public static final String TAG_DATETIME_ORIGINAL = "DateTimeOriginal"; 148 /** Type is String. */ 149 public static final String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription"; 150 /** Type is double. */ 151 public static final String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio"; 152 /** Type is String. */ 153 public static final String TAG_EXIF_VERSION = "ExifVersion"; 154 /** Type is double. */ 155 public static final String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue"; 156 /** Type is rational. */ 157 public static final String TAG_EXPOSURE_INDEX = "ExposureIndex"; 158 /** Type is int. */ 159 public static final String TAG_EXPOSURE_MODE = "ExposureMode"; 160 /** Type is int. */ 161 public static final String TAG_EXPOSURE_PROGRAM = "ExposureProgram"; 162 /** Type is double. */ 163 public static final String TAG_EXPOSURE_TIME = "ExposureTime"; 164 /** Type is String. */ 165 public static final String TAG_F_NUMBER = "FNumber"; 166 /** Type is String. */ 167 public static final String TAG_APERTURE = "FNumber"; 168 /** Type is String. */ 169 public static final String TAG_FILE_SOURCE = "FileSource"; 170 /** Type is int. */ 171 public static final String TAG_FLASH = "Flash"; 172 /** Type is rational. */ 173 public static final String TAG_FLASH_ENERGY = "FlashEnergy"; 174 /** Type is String. */ 175 public static final String TAG_FLASHPIX_VERSION = "FlashpixVersion"; 176 /** Type is rational. */ 177 public static final String TAG_FOCAL_LENGTH = "FocalLength"; 178 /** Type is int. */ 179 public static final String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm"; 180 /** Type is int. */ 181 public static final String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit"; 182 /** Type is rational. */ 183 public static final String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution"; 184 /** Type is rational. */ 185 public static final String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution"; 186 /** Type is rational. */ 187 public static final String TAG_GAIN_CONTROL = "GainControl"; 188 /** Type is String. */ 189 public static final String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings"; 190 /** Type is String. */ 191 public static final String TAG_ISO = "ISOSpeedRatings"; 192 /** Type is String. */ 193 public static final String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID"; 194 /** Type is int. */ 195 public static final String TAG_LIGHT_SOURCE = "LightSource"; 196 /** Type is String. */ 197 public static final String TAG_MAKER_NOTE = "MakerNote"; 198 /** Type is rational. */ 199 public static final String TAG_MAX_APERTURE_VALUE = "MaxApertureValue"; 200 /** Type is int. */ 201 public static final String TAG_METERING_MODE = "MeteringMode"; 202 /** Type is String. */ 203 public static final String TAG_OECF = "OECF"; 204 /** Type is int. */ 205 public static final String TAG_PIXEL_X_DIMENSION = "PixelXDimension"; 206 /** Type is int. */ 207 public static final String TAG_PIXEL_Y_DIMENSION = "PixelYDimension"; 208 /** Type is String. */ 209 public static final String TAG_RELATED_SOUND_FILE = "RelatedSoundFile"; 210 /** Type is int. */ 211 public static final String TAG_SATURATION = "Saturation"; 212 /** Type is int. */ 213 public static final String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType"; 214 /** Type is String. */ 215 public static final String TAG_SCENE_TYPE = "SceneType"; 216 /** Type is int. */ 217 public static final String TAG_SENSING_METHOD = "SensingMethod"; 218 /** Type is int. */ 219 public static final String TAG_SHARPNESS = "Sharpness"; 220 /** Type is rational. */ 221 public static final String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue"; 222 /** Type is String. */ 223 public static final String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse"; 224 /** Type is String. */ 225 public static final String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity"; 226 /** Type is int. */ 227 public static final String TAG_SUBSEC_TIME = "SubSecTime"; 228 /** Type is int. @hide */ 229 public static final String TAG_SUBSECTIME = "SubSecTime"; 230 /** Type is int. */ 231 public static final String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized"; 232 /** Type is int. */ 233 public static final String TAG_SUBSEC_TIME_DIG = "SubSecTimeDigitized"; 234 /** Type is int. */ 235 public static final String TAG_SUBSEC_TIME_ORIG = "SubSecTimeOriginal"; 236 /** Type is int. */ 237 public static final String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal"; 238 /** Type is int. */ 239 public static final String TAG_SUBJECT_AREA = "SubjectArea"; 240 /** Type is double. */ 241 public static final String TAG_SUBJECT_DISTANCE = "SubjectDistance"; 242 /** Type is int. */ 243 public static final String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange"; 244 /** Type is int. */ 245 public static final String TAG_SUBJECT_LOCATION = "SubjectLocation"; 246 /** Type is String. */ 247 public static final String TAG_USER_COMMENT = "UserComment"; 248 /** Type is int. */ 249 public static final String TAG_WHITE_BALANCE = "WhiteBalance"; 250 /** 251 * The altitude (in meters) based on the reference in TAG_GPS_ALTITUDE_REF. 252 * Type is rational. 253 */ 254 public static final String TAG_GPS_ALTITUDE = "GPSAltitude"; 255 /** 256 * 0 if the altitude is above sea level. 1 if the altitude is below sea 257 * level. Type is int. 258 */ 259 public static final String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef"; 260 /** Type is String. */ 261 public static final String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation"; 262 /** Type is rational. */ 263 public static final String TAG_GPS_DOP = "GPSDOP"; 264 /** Type is String. */ 265 public static final String TAG_GPS_DATESTAMP = "GPSDateStamp"; 266 /** Type is rational. */ 267 public static final String TAG_GPS_DEST_BEARING = "GPSDestBearing"; 268 /** Type is String. */ 269 public static final String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef"; 270 /** Type is rational. */ 271 public static final String TAG_GPS_DEST_DISTANCE = "GPSDestDistance"; 272 /** Type is String. */ 273 public static final String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef"; 274 /** Type is rational. */ 275 public static final String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude"; 276 /** Type is String. */ 277 public static final String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef"; 278 /** Type is rational. */ 279 public static final String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude"; 280 /** Type is String. */ 281 public static final String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef"; 282 /** Type is int. */ 283 public static final String TAG_GPS_DIFFERENTIAL = "GPSDifferential"; 284 /** Type is rational. */ 285 public static final String TAG_GPS_IMG_DIRECTION = "GPSImgDirection"; 286 /** Type is String. */ 287 public static final String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef"; 288 /** String. Format is "num1/denom1,num2/denom2,num3/denom3". */ 289 public static final String TAG_GPS_LATITUDE = "GPSLatitude"; 290 /** Type is String. */ 291 public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef"; 292 /** String. Format is "num1/denom1,num2/denom2,num3/denom3". */ 293 public static final String TAG_GPS_LONGITUDE = "GPSLongitude"; 294 /** Type is String. */ 295 public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef"; 296 /** Type is String. */ 297 public static final String TAG_GPS_MAP_DATUM = "GPSMapDatum"; 298 /** Type is String. */ 299 public static final String TAG_GPS_MEASURE_MODE = "GPSMeasureMode"; 300 /** Type is String. Name of GPS processing method used for location finding. */ 301 public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod"; 302 /** Type is String. */ 303 public static final String TAG_GPS_SATELLITES = "GPSSatellites"; 304 /** Type is rational. */ 305 public static final String TAG_GPS_SPEED = "GPSSpeed"; 306 /** Type is String. */ 307 public static final String TAG_GPS_SPEED_REF = "GPSSpeedRef"; 308 /** Type is String. */ 309 public static final String TAG_GPS_STATUS = "GPSStatus"; 310 /** Type is String. */ 311 public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp"; 312 /** Type is rational. */ 313 public static final String TAG_GPS_TRACK = "GPSTrack"; 314 /** Type is String. */ 315 public static final String TAG_GPS_TRACK_REF = "GPSTrackRef"; 316 /** Type is String. */ 317 public static final String TAG_GPS_VERSION_ID = "GPSVersionID"; 318 /** Type is String. */ 319 public static final String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex"; 320 /** Type is int. */ 321 public static final String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength"; 322 /** Type is int. */ 323 public static final String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth"; 324 325 // Private tags used for pointing the other IFD offset. The types of the following tags are int. 326 private static final String TAG_EXIF_IFD_POINTER = "ExifIFDPointer"; 327 private static final String TAG_GPS_INFO_IFD_POINTER = "GPSInfoIFDPointer"; 328 private static final String TAG_INTEROPERABILITY_IFD_POINTER = "InteroperabilityIFDPointer"; 329 330 // Private tags used for thumbnail information. 331 private static final String TAG_HAS_THUMBNAIL = "hasThumbnail"; 332 private static final String TAG_THUMBNAIL_OFFSET = "thumbnailOffset"; 333 private static final String TAG_THUMBNAIL_LENGTH = "thumbnailLength"; 334 private static final String TAG_THUMBNAIL_DATA = "thumbnailData"; 335 336 // Constants used for the Orientation Exif tag. 337 public static final int ORIENTATION_UNDEFINED = 0; 338 public static final int ORIENTATION_NORMAL = 1; 339 public static final int ORIENTATION_FLIP_HORIZONTAL = 2; // left right reversed mirror 340 public static final int ORIENTATION_ROTATE_180 = 3; 341 public static final int ORIENTATION_FLIP_VERTICAL = 4; // upside down mirror 342 // flipped about top-left <--> bottom-right axis 343 public static final int ORIENTATION_TRANSPOSE = 5; 344 public static final int ORIENTATION_ROTATE_90 = 6; // rotate 90 cw to right it 345 // flipped about top-right <--> bottom-left axis 346 public static final int ORIENTATION_TRANSVERSE = 7; 347 public static final int ORIENTATION_ROTATE_270 = 8; // rotate 270 to right it 348 349 // Constants used for white balance 350 public static final int WHITEBALANCE_AUTO = 0; 351 public static final int WHITEBALANCE_MANUAL = 1; 352 353 private static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff}; 354 private static final int JPEG_SIGNATURE_SIZE = 3; 355 356 private static SimpleDateFormat sFormatter; 357 358 // See Exchangeable image file format for digital still cameras: Exif version 2.2. 359 // The following values are for parsing EXIF data area. There are tag groups in EXIF data area. 360 // They are called "Image File Directory". They have multiple data formats to cover various 361 // image metadata from GPS longitude to camera model name. 362 363 // Types of Exif byte alignments (see JEITA CP-3451 page 10) 364 private static final short BYTE_ALIGN_II = 0x4949; // II: Intel order 365 private static final short BYTE_ALIGN_MM = 0x4d4d; // MM: Motorola order 366 367 // Formats for the value in IFD entry (See TIFF 6.0 spec Types page 15). 368 private static final int IFD_FORMAT_BYTE = 1; 369 private static final int IFD_FORMAT_STRING = 2; 370 private static final int IFD_FORMAT_USHORT = 3; 371 private static final int IFD_FORMAT_ULONG = 4; 372 private static final int IFD_FORMAT_URATIONAL = 5; 373 private static final int IFD_FORMAT_SBYTE = 6; 374 private static final int IFD_FORMAT_UNDEFINED = 7; 375 private static final int IFD_FORMAT_SSHORT = 8; 376 private static final int IFD_FORMAT_SLONG = 9; 377 private static final int IFD_FORMAT_SRATIONAL = 10; 378 private static final int IFD_FORMAT_SINGLE = 11; 379 private static final int IFD_FORMAT_DOUBLE = 12; 380 // Sizes of the components of each IFD value format 381 private static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] { 382 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8 383 }; 384 private static final byte[] EXIF_ASCII_PREFIX = new byte[] { 385 0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0 386 }; 387 388 // A class for indicating EXIF tag. 389 private static class ExifTag { 390 public final int number; 391 public final String name; 392 393 private ExifTag(String name, int number) { 394 this.name = name; 395 this.number = number; 396 } 397 } 398 399 // Primary image IFD TIFF tags (See JEITA CP-3451 Table 14. page 54). 400 private static final ExifTag[] IFD_TIFF_TAGS = new ExifTag[] { 401 new ExifTag(TAG_IMAGE_WIDTH, 256), 402 new ExifTag(TAG_IMAGE_LENGTH, 257), 403 new ExifTag(TAG_BITS_PER_SAMPLE, 258), 404 new ExifTag(TAG_COMPRESSION, 259), 405 new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262), 406 new ExifTag(TAG_IMAGE_DESCRIPTION, 270), 407 new ExifTag(TAG_MAKE, 271), 408 new ExifTag(TAG_MODEL, 272), 409 new ExifTag(TAG_STRIP_OFFSETS, 273), 410 new ExifTag(TAG_ORIENTATION, 274), 411 new ExifTag(TAG_SAMPLES_PER_PIXEL, 277), 412 new ExifTag(TAG_ROWS_PER_STRIP, 278), 413 new ExifTag(TAG_STRIP_BYTE_COUNTS, 279), 414 new ExifTag(TAG_X_RESOLUTION, 282), 415 new ExifTag(TAG_Y_RESOLUTION, 283), 416 new ExifTag(TAG_PLANAR_CONFIGURATION, 284), 417 new ExifTag(TAG_RESOLUTION_UNIT, 296), 418 new ExifTag(TAG_TRANSFER_FUNCTION, 301), 419 new ExifTag(TAG_SOFTWARE, 305), 420 new ExifTag(TAG_DATETIME, 306), 421 new ExifTag(TAG_ARTIST, 315), 422 new ExifTag(TAG_WHITE_POINT, 318), 423 new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319), 424 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513), 425 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514), 426 new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529), 427 new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530), 428 new ExifTag(TAG_Y_CB_CR_POSITIONING, 531), 429 new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532), 430 new ExifTag(TAG_COPYRIGHT, 33432), 431 new ExifTag(TAG_EXIF_IFD_POINTER, 34665), 432 new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853), 433 }; 434 // Primary image IFD Exif Private tags (See JEITA CP-3451 Table 15. page 55). 435 private static final ExifTag[] IFD_EXIF_TAGS = new ExifTag[] { 436 new ExifTag(TAG_EXPOSURE_TIME, 33434), 437 new ExifTag(TAG_F_NUMBER, 33437), 438 new ExifTag(TAG_EXPOSURE_PROGRAM, 34850), 439 new ExifTag(TAG_SPECTRAL_SENSITIVITY, 34852), 440 new ExifTag(TAG_ISO, 34855), 441 new ExifTag(TAG_OECF, 34856), 442 new ExifTag(TAG_EXIF_VERSION, 36864), 443 new ExifTag(TAG_DATETIME_ORIGINAL, 36867), 444 new ExifTag(TAG_DATETIME_DIGITIZED, 36868), 445 new ExifTag(TAG_COMPONENTS_CONFIGURATION, 37121), 446 new ExifTag(TAG_COMPRESSED_BITS_PER_PIXEL, 37122), 447 new ExifTag(TAG_SHUTTER_SPEED_VALUE, 37377), 448 new ExifTag(TAG_APERTURE_VALUE, 37378), 449 new ExifTag(TAG_BRIGHTNESS_VALUE, 37379), 450 new ExifTag(TAG_EXPOSURE_BIAS_VALUE, 37380), 451 new ExifTag(TAG_MAX_APERTURE_VALUE, 37381), 452 new ExifTag(TAG_SUBJECT_DISTANCE, 37382), 453 new ExifTag(TAG_METERING_MODE, 37383), 454 new ExifTag(TAG_LIGHT_SOURCE, 37384), 455 new ExifTag(TAG_FLASH, 37385), 456 new ExifTag(TAG_FOCAL_LENGTH, 37386), 457 new ExifTag(TAG_SUBJECT_AREA, 37396), 458 new ExifTag(TAG_MAKER_NOTE, 37500), 459 new ExifTag(TAG_USER_COMMENT, 37510), 460 new ExifTag(TAG_SUBSEC_TIME, 37520), 461 new ExifTag(TAG_SUBSEC_TIME_ORIG, 37521), 462 new ExifTag(TAG_SUBSEC_TIME_DIG, 37522), 463 new ExifTag(TAG_FLASHPIX_VERSION, 40960), 464 new ExifTag(TAG_COLOR_SPACE, 40961), 465 new ExifTag(TAG_PIXEL_X_DIMENSION, 40962), 466 new ExifTag(TAG_PIXEL_Y_DIMENSION, 40963), 467 new ExifTag(TAG_RELATED_SOUND_FILE, 40964), 468 new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965), 469 new ExifTag(TAG_FLASH_ENERGY, 41483), 470 new ExifTag(TAG_SPATIAL_FREQUENCY_RESPONSE, 41484), 471 new ExifTag(TAG_FOCAL_PLANE_X_RESOLUTION, 41486), 472 new ExifTag(TAG_FOCAL_PLANE_Y_RESOLUTION, 41487), 473 new ExifTag(TAG_FOCAL_PLANE_RESOLUTION_UNIT, 41488), 474 new ExifTag(TAG_SUBJECT_LOCATION, 41492), 475 new ExifTag(TAG_EXPOSURE_INDEX, 41493), 476 new ExifTag(TAG_SENSING_METHOD, 41495), 477 new ExifTag(TAG_FILE_SOURCE, 41728), 478 new ExifTag(TAG_SCENE_TYPE, 41729), 479 new ExifTag(TAG_CFA_PATTERN, 41730), 480 new ExifTag(TAG_CUSTOM_RENDERED, 41985), 481 new ExifTag(TAG_EXPOSURE_MODE, 41986), 482 new ExifTag(TAG_WHITE_BALANCE, 41987), 483 new ExifTag(TAG_DIGITAL_ZOOM_RATIO, 41988), 484 new ExifTag(TAG_FOCAL_LENGTH_IN_35MM_FILM, 41989), 485 new ExifTag(TAG_SCENE_CAPTURE_TYPE, 41990), 486 new ExifTag(TAG_GAIN_CONTROL, 41991), 487 new ExifTag(TAG_CONTRAST, 41992), 488 new ExifTag(TAG_SATURATION, 41993), 489 new ExifTag(TAG_SHARPNESS, 41994), 490 new ExifTag(TAG_DEVICE_SETTING_DESCRIPTION, 41995), 491 new ExifTag(TAG_SUBJECT_DISTANCE_RANGE, 41996), 492 new ExifTag(TAG_IMAGE_UNIQUE_ID, 42016), 493 }; 494 // Primary image IFD GPS Info tags (See JEITA CP-3451 Table 16. page 56). 495 private static final ExifTag[] IFD_GPS_TAGS = new ExifTag[] { 496 new ExifTag(TAG_GPS_VERSION_ID, 0), 497 new ExifTag(TAG_GPS_LATITUDE_REF, 1), 498 new ExifTag(TAG_GPS_LATITUDE, 2), 499 new ExifTag(TAG_GPS_LONGITUDE_REF, 3), 500 new ExifTag(TAG_GPS_LONGITUDE, 4), 501 new ExifTag(TAG_GPS_ALTITUDE_REF, 5), 502 new ExifTag(TAG_GPS_ALTITUDE, 6), 503 new ExifTag(TAG_GPS_TIMESTAMP, 7), 504 new ExifTag(TAG_GPS_SATELLITES, 8), 505 new ExifTag(TAG_GPS_STATUS, 9), 506 new ExifTag(TAG_GPS_MEASURE_MODE, 10), 507 new ExifTag(TAG_GPS_DOP, 11), 508 new ExifTag(TAG_GPS_SPEED_REF, 12), 509 new ExifTag(TAG_GPS_SPEED, 13), 510 new ExifTag(TAG_GPS_TRACK_REF, 14), 511 new ExifTag(TAG_GPS_TRACK, 15), 512 new ExifTag(TAG_GPS_IMG_DIRECTION_REF, 16), 513 new ExifTag(TAG_GPS_IMG_DIRECTION, 17), 514 new ExifTag(TAG_GPS_MAP_DATUM, 18), 515 new ExifTag(TAG_GPS_DEST_LATITUDE_REF, 19), 516 new ExifTag(TAG_GPS_DEST_LATITUDE, 20), 517 new ExifTag(TAG_GPS_DEST_LONGITUDE_REF, 21), 518 new ExifTag(TAG_GPS_DEST_LONGITUDE, 22), 519 new ExifTag(TAG_GPS_DEST_BEARING_REF, 23), 520 new ExifTag(TAG_GPS_DEST_BEARING, 24), 521 new ExifTag(TAG_GPS_DEST_DISTANCE_REF, 25), 522 new ExifTag(TAG_GPS_DEST_DISTANCE, 26), 523 new ExifTag(TAG_GPS_PROCESSING_METHOD, 27), 524 new ExifTag(TAG_GPS_AREA_INFORMATION, 28), 525 new ExifTag(TAG_GPS_DATESTAMP, 29), 526 new ExifTag(TAG_GPS_DIFFERENTIAL, 30), 527 }; 528 // Primary image IFD Interoperability tag (See JEITA CP-3451 Table 17. page 56). 529 private static final ExifTag[] IFD_INTEROPERABILITY_TAGS = new ExifTag[] { 530 new ExifTag(TAG_INTEROPERABILITY_INDEX, 1), 531 }; 532 // IFD Thumbnail tags (See JEITA CP-3451 Table 18. page 57). 533 private static final ExifTag[] IFD_THUMBNAIL_TAGS = new ExifTag[] { 534 new ExifTag(TAG_THUMBNAIL_IMAGE_WIDTH, 256), 535 new ExifTag(TAG_THUMBNAIL_IMAGE_LENGTH, 257), 536 new ExifTag(TAG_BITS_PER_SAMPLE, 258), 537 new ExifTag(TAG_COMPRESSION, 259), 538 new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262), 539 new ExifTag(TAG_IMAGE_DESCRIPTION, 270), 540 new ExifTag(TAG_MAKE, 271), 541 new ExifTag(TAG_MODEL, 272), 542 new ExifTag(TAG_STRIP_OFFSETS, 273), 543 new ExifTag(TAG_ORIENTATION, 274), 544 new ExifTag(TAG_SAMPLES_PER_PIXEL, 277), 545 new ExifTag(TAG_ROWS_PER_STRIP, 278), 546 new ExifTag(TAG_STRIP_BYTE_COUNTS, 279), 547 new ExifTag(TAG_X_RESOLUTION, 282), 548 new ExifTag(TAG_Y_RESOLUTION, 283), 549 new ExifTag(TAG_PLANAR_CONFIGURATION, 284), 550 new ExifTag(TAG_RESOLUTION_UNIT, 296), 551 new ExifTag(TAG_TRANSFER_FUNCTION, 301), 552 new ExifTag(TAG_SOFTWARE, 305), 553 new ExifTag(TAG_DATETIME, 306), 554 new ExifTag(TAG_ARTIST, 315), 555 new ExifTag(TAG_WHITE_POINT, 318), 556 new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319), 557 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513), 558 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514), 559 new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529), 560 new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530), 561 new ExifTag(TAG_Y_CB_CR_POSITIONING, 531), 562 new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532), 563 new ExifTag(TAG_COPYRIGHT, 33432), 564 new ExifTag(TAG_EXIF_IFD_POINTER, 34665), 565 new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853), 566 }; 567 568 // See JEITA CP-3451 Figure 5. page 9. 569 // The following values are used for indicating pointers to the other Image File Directorys. 570 571 // Indices of Exif Ifd tag groups 572 private static final int IFD_TIFF_HINT = 0; 573 private static final int IFD_EXIF_HINT = 1; 574 private static final int IFD_GPS_HINT = 2; 575 private static final int IFD_INTEROPERABILITY_HINT = 3; 576 private static final int IFD_THUMBNAIL_HINT = 4; 577 // List of Exif tag groups 578 private static final ExifTag[][] EXIF_TAGS = new ExifTag[][] { 579 IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS, 580 IFD_THUMBNAIL_TAGS 581 }; 582 // List of tags for pointing to the other image file directory offset. 583 private static final ExifTag[] IFD_POINTER_TAGS = new ExifTag[] { 584 new ExifTag(TAG_EXIF_IFD_POINTER, 34665), 585 new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853), 586 new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965), 587 }; 588 // List of indices of the indicated tag groups according to the IFD_POINTER_TAGS 589 private static final int[] IFD_POINTER_TAG_HINTS = new int[] { 590 IFD_EXIF_HINT, IFD_GPS_HINT, IFD_INTEROPERABILITY_HINT 591 }; 592 // Tags for indicating the thumbnail offset and length 593 private static final ExifTag JPEG_INTERCHANGE_FORMAT_TAG = 594 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513); 595 private static final ExifTag JPEG_INTERCHANGE_FORMAT_LENGTH_TAG = 596 new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514); 597 598 // Mappings from tag number to tag name and each item represents one IFD tag group. 599 private static final HashMap[] sExifTagMapsForReading = new HashMap[EXIF_TAGS.length]; 600 // Mappings from tag name to tag number and each item represents one IFD tag group. 601 private static final HashMap[] sExifTagMapsForWriting = new HashMap[EXIF_TAGS.length]; 602 603 // See JPEG File Interchange Format Version 1.02. 604 // The following values are defined for handling JPEG streams. In this implementation, we are 605 // not only getting information from EXIF but also from some JPEG special segments such as 606 // MARKER_COM for user comment and MARKER_SOFx for image width and height. 607 608 // Identifier for APP1 segment in JPEG 609 private static final byte[] IDENTIFIER_APP1 = "Exif\0\0".getBytes(Charset.forName("US-ASCII")); 610 // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with 611 // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start 612 // of frame(baseline DCT) and the image size info exists in its beginning part. 613 private static final byte MARKER = (byte) 0xff; 614 private static final byte MARKER_SOI = (byte) 0xd8; 615 private static final byte MARKER_SOF0 = (byte) 0xc0; 616 private static final byte MARKER_SOF1 = (byte) 0xc1; 617 private static final byte MARKER_SOF2 = (byte) 0xc2; 618 private static final byte MARKER_SOF3 = (byte) 0xc3; 619 private static final byte MARKER_SOF5 = (byte) 0xc5; 620 private static final byte MARKER_SOF6 = (byte) 0xc6; 621 private static final byte MARKER_SOF7 = (byte) 0xc7; 622 private static final byte MARKER_SOF9 = (byte) 0xc9; 623 private static final byte MARKER_SOF10 = (byte) 0xca; 624 private static final byte MARKER_SOF11 = (byte) 0xcb; 625 private static final byte MARKER_SOF13 = (byte) 0xcd; 626 private static final byte MARKER_SOF14 = (byte) 0xce; 627 private static final byte MARKER_SOF15 = (byte) 0xcf; 628 private static final byte MARKER_SOS = (byte) 0xda; 629 private static final byte MARKER_APP1 = (byte) 0xe1; 630 private static final byte MARKER_COM = (byte) 0xfe; 631 private static final byte MARKER_EOI = (byte) 0xd9; 632 633 static { 634 System.loadLibrary("media_jni"); 635 nativeInitRaw(); 636 sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); 637 sFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); 638 639 // Build up the hash tables to look up Exif tags for reading Exif tags. 640 for (int hint = 0; hint < EXIF_TAGS.length; ++hint) { 641 sExifTagMapsForReading[hint] = new HashMap(); 642 sExifTagMapsForWriting[hint] = new HashMap(); 643 for (ExifTag tag : EXIF_TAGS[hint]) { 644 sExifTagMapsForReading[hint].put(tag.number, tag.name); 645 sExifTagMapsForWriting[hint].put(tag.name, tag.number); 646 } 647 } 648 } 649 650 private final String mFilename; 651 private final FileDescriptor mSeekableFileDescriptor; 652 private final AssetManager.AssetInputStream mAssetInputStream; 653 private boolean mIsRaw; 654 private final HashMap[] mAttributes = new HashMap[EXIF_TAGS.length]; 655 private boolean mHasThumbnail; 656 // The following values used for indicating a thumbnail position. 657 private int mThumbnailOffset; 658 private int mThumbnailLength; 659 private byte[] mThumbnailBytes; 660 661 // Pattern to check non zero timestamp 662 private static final Pattern sNonZeroTimePattern = Pattern.compile(".*[1-9].*"); 663 664 /** 665 * Reads Exif tags from the specified image file. 666 */ 667 public ExifInterface(String filename) throws IOException { 668 if (filename == null) { 669 throw new IllegalArgumentException("filename cannot be null"); 670 } 671 FileInputStream in = new FileInputStream(filename); 672 mAssetInputStream = null; 673 mFilename = filename; 674 if (isSeekableFD(in.getFD())) { 675 mSeekableFileDescriptor = in.getFD(); 676 } else { 677 mSeekableFileDescriptor = null; 678 } 679 loadAttributes(in); 680 } 681 682 /** 683 * Reads Exif tags from the specified image file descriptor. Attribute mutation is supported 684 * for seekable file descriptors only. 685 */ 686 public ExifInterface(FileDescriptor fileDescriptor) throws IOException { 687 if (fileDescriptor == null) { 688 throw new IllegalArgumentException("parcelFileDescriptor cannot be null"); 689 } 690 mAssetInputStream = null; 691 mFilename = null; 692 if (isSeekableFD(fileDescriptor)) { 693 mSeekableFileDescriptor = fileDescriptor; 694 } else { 695 mSeekableFileDescriptor = null; 696 } 697 loadAttributes(new FileInputStream(fileDescriptor)); 698 } 699 700 /** 701 * Reads Exif tags from the specified image input stream. Attribute mutation is not supported 702 * for input streams. 703 */ 704 public ExifInterface(InputStream inputStream) throws IOException { 705 if (inputStream == null) { 706 throw new IllegalArgumentException("inputStream cannot be null"); 707 } 708 mFilename = null; 709 if (inputStream instanceof AssetManager.AssetInputStream) { 710 mAssetInputStream = (AssetManager.AssetInputStream) inputStream; 711 mSeekableFileDescriptor = null; 712 } else if (inputStream instanceof FileInputStream 713 && isSeekableFD(((FileInputStream) inputStream).getFD())) { 714 mAssetInputStream = null; 715 mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD(); 716 } else { 717 mAssetInputStream = null; 718 mSeekableFileDescriptor = null; 719 } 720 loadAttributes(inputStream); 721 } 722 723 /** 724 * Returns the value of the specified tag or {@code null} if there 725 * is no such tag in the image file. 726 * 727 * @param tag the name of the tag. 728 */ 729 public String getAttribute(String tag) { 730 // Retrieves all tag groups. The value from primary image tag group has a higher priority 731 // than the value from the thumbnail tag group if there are more than one candidates. 732 for (int i = 0; i < EXIF_TAGS.length; ++i) { 733 Object value = mAttributes[i].get(tag); 734 if (value != null) { 735 return (String) value; 736 } 737 } 738 return null; 739 } 740 741 /** 742 * Returns the integer value of the specified tag. If there is no such tag 743 * in the image file or the value cannot be parsed as integer, return 744 * <var>defaultValue</var>. 745 * 746 * @param tag the name of the tag. 747 * @param defaultValue the value to return if the tag is not available. 748 */ 749 public int getAttributeInt(String tag, int defaultValue) { 750 String value = getAttribute(tag); 751 if (value == null) return defaultValue; 752 try { 753 return Integer.valueOf(value); 754 } catch (NumberFormatException e) { 755 return defaultValue; 756 } 757 } 758 759 /** 760 * Returns the double value of the tag that is specified as rational or contains a 761 * double-formatted value. If there is no such tag in the image file or the value cannot be 762 * parsed as double, return <var>defaultValue</var>. 763 * 764 * @param tag the name of the tag. 765 * @param defaultValue the value to return if the tag is not available. 766 */ 767 public double getAttributeDouble(String tag, double defaultValue) { 768 String value = getAttribute(tag); 769 if (value == null) return defaultValue; 770 try { 771 int index = value.indexOf("/"); 772 if (index == -1) return Double.parseDouble(value); 773 double denom = Double.parseDouble(value.substring(index + 1)); 774 if (denom == 0) return defaultValue; 775 double num = Double.parseDouble(value.substring(0, index)); 776 return num / denom; 777 } catch (NumberFormatException e) { 778 return defaultValue; 779 } 780 } 781 782 /** 783 * Set the value of the specified tag. 784 * 785 * @param tag the name of the tag. 786 * @param value the value of the tag. 787 */ 788 public void setAttribute(String tag, String value) { 789 for (int i = 0 ; i < EXIF_TAGS.length; ++i) { 790 if (sExifTagMapsForWriting[i].containsKey(tag)) { 791 mAttributes[i].put(tag, value); 792 } 793 } 794 } 795 796 /** 797 * This function decides which parser to read the image data according to the given input stream 798 * type and the content of the input stream. In each case, it reads the first three bytes to 799 * determine whether the image data format is JPEG or not. 800 */ 801 private void loadAttributes(@NonNull InputStream in) throws IOException { 802 // Initialize mAttributes. 803 for (int i = 0; i < EXIF_TAGS.length; ++i) { 804 mAttributes[i] = new HashMap(); 805 } 806 807 // Process RAW input stream 808 if (mAssetInputStream != null) { 809 long asset = mAssetInputStream.getNativeAsset(); 810 if (handleRawResult(nativeGetRawAttributesFromAsset(asset))) { 811 return; 812 } 813 } else if (mSeekableFileDescriptor != null) { 814 if (handleRawResult(nativeGetRawAttributesFromFileDescriptor( 815 mSeekableFileDescriptor))) { 816 return; 817 } 818 } else { 819 in = new BufferedInputStream(in, JPEG_SIGNATURE_SIZE); 820 if (!isJpegInputStream((BufferedInputStream) in) && handleRawResult( 821 nativeGetRawAttributesFromInputStream(in))) { 822 return; 823 } 824 } 825 826 // Process JPEG input stream 827 try { 828 getJpegAttributes(in); 829 } catch (IOException e) { 830 // Ignore exceptions in order to keep the compatibility with the old versions of 831 // ExifInterface. 832 Log.w(TAG, "Invalid JPEG", e); 833 } 834 835 if (DEBUG) { 836 printAttributes(); 837 } 838 } 839 840 private static boolean isJpegInputStream(BufferedInputStream in) throws IOException { 841 in.mark(JPEG_SIGNATURE_SIZE); 842 byte[] signatureBytes = new byte[JPEG_SIGNATURE_SIZE]; 843 if (in.read(signatureBytes) != JPEG_SIGNATURE_SIZE) { 844 throw new EOFException(); 845 } 846 boolean isJpeg = Arrays.equals(JPEG_SIGNATURE, signatureBytes); 847 in.reset(); 848 return isJpeg; 849 } 850 851 private boolean handleRawResult(HashMap map) { 852 if (map == null) { 853 return false; 854 } 855 856 // Mark for disabling the save feature. 857 mIsRaw = true; 858 859 for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) { 860 String attrName = (String) entry.getKey(); 861 862 switch (attrName) { 863 case TAG_HAS_THUMBNAIL: 864 mHasThumbnail = ((String) entry.getValue()).equalsIgnoreCase("true"); 865 break; 866 case TAG_THUMBNAIL_OFFSET: 867 mThumbnailOffset = Integer.parseInt((String) entry.getValue()); 868 break; 869 case TAG_THUMBNAIL_LENGTH: 870 mThumbnailLength = Integer.parseInt((String) entry.getValue()); 871 break; 872 case TAG_THUMBNAIL_DATA: 873 mThumbnailBytes = (byte[]) entry.getValue(); 874 break; 875 default: 876 setAttribute(attrName, (String) entry.getValue()); 877 break; 878 } 879 } 880 881 if (DEBUG) { 882 printAttributes(); 883 } 884 return true; 885 } 886 887 private static boolean isSeekableFD(FileDescriptor fd) throws IOException { 888 try { 889 Os.lseek(fd, 0, OsConstants.SEEK_CUR); 890 return true; 891 } catch (ErrnoException e) { 892 return false; 893 } 894 } 895 896 // Prints out attributes for debugging. 897 private void printAttributes() { 898 for (int i = 0; i < mAttributes.length; ++i) { 899 Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size()); 900 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) { 901 Log.d(TAG, "tagName: " + entry.getKey() + ", tagValue: " + entry.getValue()); 902 } 903 } 904 } 905 906 /** 907 * Save the tag data into the original image file. This is expensive because it involves 908 * copying all the data from one file to another and deleting the old file and renaming the 909 * other. It's best to use{@link #setAttribute(String,String)} to set all attributes to write 910 * and make a single call rather than multiple calls for each attribute. 911 */ 912 public void saveAttributes() throws IOException { 913 if (mIsRaw) { 914 throw new UnsupportedOperationException( 915 "ExifInterface does not support saving attributes on RAW formats."); 916 } 917 if (mSeekableFileDescriptor == null && mFilename == null) { 918 throw new UnsupportedOperationException( 919 "ExifInterface does not support saving attributes for the current input."); 920 } 921 922 // Keep the thumbnail in memory 923 mThumbnailBytes = getThumbnail(); 924 925 FileInputStream in = null; 926 FileOutputStream out = null; 927 File tempFile = null; 928 try { 929 // Move the original file to temporary file. 930 if (mFilename != null) { 931 tempFile = new File(mFilename + ".tmp"); 932 File originalFile = new File(mFilename); 933 if (!originalFile.renameTo(tempFile)) { 934 throw new IOException("Could'nt rename to " + tempFile.getAbsolutePath()); 935 } 936 } else if (mSeekableFileDescriptor != null) { 937 tempFile = File.createTempFile("temp", "jpg"); 938 Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET); 939 in = new FileInputStream(mSeekableFileDescriptor); 940 out = new FileOutputStream(tempFile); 941 Streams.copy(in, out); 942 } 943 } catch (ErrnoException e) { 944 e.rethrowAsIOException(); 945 } finally { 946 IoUtils.closeQuietly(in); 947 IoUtils.closeQuietly(out); 948 } 949 950 in = null; 951 out = null; 952 try { 953 // Save the new file. 954 in = new FileInputStream(tempFile); 955 if (mFilename != null) { 956 out = new FileOutputStream(mFilename); 957 } else if (mSeekableFileDescriptor != null) { 958 Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET); 959 out = new FileOutputStream(mSeekableFileDescriptor); 960 } 961 saveJpegAttributes(in, out); 962 } catch (ErrnoException e) { 963 e.rethrowAsIOException(); 964 } finally { 965 IoUtils.closeQuietly(in); 966 IoUtils.closeQuietly(out); 967 tempFile.delete(); 968 } 969 970 // Discard the thumbnail in memory 971 mThumbnailBytes = null; 972 } 973 974 /** 975 * Returns true if the image file has a thumbnail. 976 */ 977 public boolean hasThumbnail() { 978 return mHasThumbnail; 979 } 980 981 /** 982 * Returns the thumbnail inside the image file, or {@code null} if there is no thumbnail. 983 * The returned data is in JPEG format and can be decoded using 984 * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)} 985 */ 986 public byte[] getThumbnail() { 987 if (!mHasThumbnail) { 988 return null; 989 } 990 if (mThumbnailBytes != null) { 991 return mThumbnailBytes; 992 } 993 994 // Read the thumbnail. 995 FileInputStream in = null; 996 try { 997 if (mAssetInputStream != null) { 998 return nativeGetThumbnailFromAsset( 999 mAssetInputStream.getNativeAsset(), mThumbnailOffset, mThumbnailLength); 1000 } else if (mFilename != null) { 1001 in = new FileInputStream(mFilename); 1002 } else if (mSeekableFileDescriptor != null) { 1003 Os.lseek(mSeekableFileDescriptor, 0, OsConstants.SEEK_SET); 1004 in = new FileInputStream(mSeekableFileDescriptor); 1005 } 1006 if (in == null) { 1007 // Should not be reached this. 1008 throw new FileNotFoundException(); 1009 } 1010 if (in.skip(mThumbnailOffset) != mThumbnailOffset) { 1011 throw new IOException("Corrupted image"); 1012 } 1013 byte[] buffer = new byte[mThumbnailLength]; 1014 if (in.read(buffer) != mThumbnailLength) { 1015 throw new IOException("Corrupted image"); 1016 } 1017 return buffer; 1018 } catch (IOException | ErrnoException e) { 1019 // Couldn't get a thumbnail image. 1020 } finally { 1021 IoUtils.closeQuietly(in); 1022 } 1023 return null; 1024 } 1025 1026 /** 1027 * Returns the offset and length of thumbnail inside the image file, or 1028 * {@code null} if there is no thumbnail. 1029 * 1030 * @return two-element array, the offset in the first value, and length in 1031 * the second, or {@code null} if no thumbnail was found. 1032 * @hide 1033 */ 1034 public long[] getThumbnailRange() { 1035 long[] range = new long[2]; 1036 range[0] = mThumbnailOffset; 1037 range[1] = mThumbnailLength; 1038 return range; 1039 } 1040 1041 /** 1042 * Stores the latitude and longitude value in a float array. The first element is 1043 * the latitude, and the second element is the longitude. Returns false if the 1044 * Exif tags are not available. 1045 */ 1046 public boolean getLatLong(float output[]) { 1047 String latValue = getAttribute(TAG_GPS_LATITUDE); 1048 String latRef = getAttribute(TAG_GPS_LATITUDE_REF); 1049 String lngValue = getAttribute(TAG_GPS_LONGITUDE); 1050 String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF); 1051 1052 if (latValue != null && latRef != null && lngValue != null && lngRef != null) { 1053 try { 1054 output[0] = convertRationalLatLonToFloat(latValue, latRef); 1055 output[1] = convertRationalLatLonToFloat(lngValue, lngRef); 1056 return true; 1057 } catch (IllegalArgumentException e) { 1058 // if values are not parseable 1059 } 1060 } 1061 1062 return false; 1063 } 1064 1065 /** 1066 * Return the altitude in meters. If the exif tag does not exist, return 1067 * <var>defaultValue</var>. 1068 * 1069 * @param defaultValue the value to return if the tag is not available. 1070 */ 1071 public double getAltitude(double defaultValue) { 1072 double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1); 1073 int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1); 1074 1075 if (altitude >= 0 && ref >= 0) { 1076 return (altitude * ((ref == 1) ? -1 : 1)); 1077 } else { 1078 return defaultValue; 1079 } 1080 } 1081 1082 /** 1083 * Returns number of milliseconds since Jan. 1, 1970, midnight local time. 1084 * Returns -1 if the date time information if not available. 1085 * @hide 1086 */ 1087 public long getDateTime() { 1088 String dateTimeString = getAttribute(TAG_DATETIME); 1089 if (dateTimeString == null 1090 || !sNonZeroTimePattern.matcher(dateTimeString).matches()) return -1; 1091 1092 ParsePosition pos = new ParsePosition(0); 1093 try { 1094 // The exif field is in local time. Parsing it as if it is UTC will yield time 1095 // since 1/1/1970 local time 1096 Date datetime = sFormatter.parse(dateTimeString, pos); 1097 if (datetime == null) return -1; 1098 long msecs = datetime.getTime(); 1099 1100 String subSecs = getAttribute(TAG_SUBSECTIME); 1101 if (subSecs != null) { 1102 try { 1103 long sub = Long.valueOf(subSecs); 1104 while (sub > 1000) { 1105 sub /= 10; 1106 } 1107 msecs += sub; 1108 } catch (NumberFormatException e) { 1109 // Ignored 1110 } 1111 } 1112 return msecs; 1113 } catch (IllegalArgumentException e) { 1114 return -1; 1115 } 1116 } 1117 1118 /** 1119 * Returns number of milliseconds since Jan. 1, 1970, midnight UTC. 1120 * Returns -1 if the date time information if not available. 1121 * @hide 1122 */ 1123 public long getGpsDateTime() { 1124 String date = getAttribute(TAG_GPS_DATESTAMP); 1125 String time = getAttribute(TAG_GPS_TIMESTAMP); 1126 if (date == null || time == null 1127 || (!sNonZeroTimePattern.matcher(date).matches() 1128 && !sNonZeroTimePattern.matcher(time).matches())) return -1; 1129 1130 String dateTimeString = date + ' ' + time; 1131 1132 ParsePosition pos = new ParsePosition(0); 1133 try { 1134 Date datetime = sFormatter.parse(dateTimeString, pos); 1135 if (datetime == null) return -1; 1136 return datetime.getTime(); 1137 } catch (IllegalArgumentException e) { 1138 return -1; 1139 } 1140 } 1141 1142 private static float convertRationalLatLonToFloat(String rationalString, String ref) { 1143 try { 1144 String [] parts = rationalString.split(","); 1145 1146 String [] pair; 1147 pair = parts[0].split("/"); 1148 double degrees = Double.parseDouble(pair[0].trim()) 1149 / Double.parseDouble(pair[1].trim()); 1150 1151 pair = parts[1].split("/"); 1152 double minutes = Double.parseDouble(pair[0].trim()) 1153 / Double.parseDouble(pair[1].trim()); 1154 1155 pair = parts[2].split("/"); 1156 double seconds = Double.parseDouble(pair[0].trim()) 1157 / Double.parseDouble(pair[1].trim()); 1158 1159 double result = degrees + (minutes / 60.0) + (seconds / 3600.0); 1160 if ((ref.equals("S") || ref.equals("W"))) { 1161 return (float) -result; 1162 } 1163 return (float) result; 1164 } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { 1165 // Not valid 1166 throw new IllegalArgumentException(); 1167 } 1168 } 1169 1170 // Loads EXIF attributes from a JPEG input stream. 1171 private void getJpegAttributes(InputStream inputStream) throws IOException { 1172 // See JPEG File Interchange Format Specification page 5. 1173 if (DEBUG) { 1174 Log.d(TAG, "getJpegAttributes starting with: " + inputStream); 1175 } 1176 DataInputStream dataInputStream = new DataInputStream(inputStream); 1177 byte marker; 1178 int bytesRead = 0; 1179 ++bytesRead; 1180 if ((marker = dataInputStream.readByte()) != MARKER) { 1181 throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); 1182 } 1183 ++bytesRead; 1184 if (dataInputStream.readByte() != MARKER_SOI) { 1185 throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); 1186 } 1187 while (true) { 1188 ++bytesRead; 1189 marker = dataInputStream.readByte(); 1190 if (marker != MARKER) { 1191 throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff)); 1192 } 1193 ++bytesRead; 1194 marker = dataInputStream.readByte(); 1195 if (DEBUG) { 1196 Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff)); 1197 } 1198 1199 // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and 1200 // the image data will terminate right after. 1201 if (marker == MARKER_EOI || marker == MARKER_SOS) { 1202 break; 1203 } 1204 bytesRead += 2; 1205 int length = dataInputStream.readUnsignedShort() - 2; 1206 if (length < 0) { 1207 throw new IOException("Invalid length"); 1208 } 1209 bytesRead += length; 1210 switch (marker) { 1211 case MARKER_APP1: { 1212 if (DEBUG) { 1213 Log.d(TAG, "MARKER_APP1"); 1214 } 1215 bytesRead -= length; 1216 if (length < 6) { 1217 throw new IOException("Invalid exif"); 1218 } 1219 byte[] identifier = new byte[6]; 1220 if (inputStream.read(identifier) != 6) { 1221 throw new IOException("Invalid exif"); 1222 } 1223 if (!Arrays.equals(identifier, IDENTIFIER_APP1)) { 1224 throw new IOException("Invalid app1 identifier"); 1225 } 1226 bytesRead += 6; 1227 length -= 6; 1228 if (length <= 0) { 1229 throw new IOException("Invalid exif"); 1230 } 1231 if (DEBUG) { 1232 Log.d(TAG, "readExifSegment with a byte array (length: " + length + ")"); 1233 } 1234 byte[] bytes = new byte[length]; 1235 if (dataInputStream.read(bytes) != length) { 1236 throw new IOException("Invalid exif"); 1237 } 1238 readExifSegment(bytes, bytesRead); 1239 bytesRead += length; 1240 length = 0; 1241 break; 1242 } 1243 1244 case MARKER_COM: { 1245 byte[] bytes = new byte[length]; 1246 if (dataInputStream.read(bytes) != length) { 1247 throw new IOException("Invalid exif"); 1248 } 1249 setAttribute("UserComment", new String(bytes, Charset.forName("US-ASCII"))); 1250 break; 1251 } 1252 1253 case MARKER_SOF0: 1254 case MARKER_SOF1: 1255 case MARKER_SOF2: 1256 case MARKER_SOF3: 1257 case MARKER_SOF5: 1258 case MARKER_SOF6: 1259 case MARKER_SOF7: 1260 case MARKER_SOF9: 1261 case MARKER_SOF10: 1262 case MARKER_SOF11: 1263 case MARKER_SOF13: 1264 case MARKER_SOF14: 1265 case MARKER_SOF15: { 1266 dataInputStream.skipBytes(1); 1267 setAttribute("ImageLength", 1268 String.valueOf(dataInputStream.readUnsignedShort())); 1269 setAttribute("ImageWidth", String.valueOf(dataInputStream.readUnsignedShort())); 1270 length -= 5; 1271 break; 1272 } 1273 1274 default: { 1275 break; 1276 } 1277 } 1278 if (length < 0) { 1279 throw new IOException("Invalid length"); 1280 } 1281 dataInputStream.skipBytes(length); 1282 } 1283 } 1284 1285 // Stores a new JPEG image with EXIF attributes into a given output stream. 1286 private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream) 1287 throws IOException { 1288 // See JPEG File Interchange Format Specification page 5. 1289 if (DEBUG) { 1290 Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream 1291 + ", outputStream: " + outputStream + ")"); 1292 } 1293 DataInputStream dataInputStream = new DataInputStream(inputStream); 1294 ExifDataOutputStream dataOutputStream = new ExifDataOutputStream(outputStream); 1295 int bytesRead = 0; 1296 ++bytesRead; 1297 if (dataInputStream.readByte() != MARKER) { 1298 throw new IOException("Invalid marker"); 1299 } 1300 dataOutputStream.writeByte(MARKER); 1301 ++bytesRead; 1302 if (dataInputStream.readByte() != MARKER_SOI) { 1303 throw new IOException("Invalid marker"); 1304 } 1305 dataOutputStream.writeByte(MARKER_SOI); 1306 1307 byte[] bytes = new byte[4096]; 1308 1309 while (true) { 1310 ++bytesRead; 1311 if (dataInputStream.readByte() != MARKER) { 1312 throw new IOException("Invalid marker"); 1313 } 1314 dataOutputStream.writeByte(MARKER); 1315 ++bytesRead; 1316 byte marker = dataInputStream.readByte(); 1317 dataOutputStream.writeByte(marker); 1318 switch (marker) { 1319 case MARKER_APP1: { 1320 // Rewrite EXIF segment 1321 int length = dataInputStream.readUnsignedShort() - 2; 1322 if (length < 0) { 1323 throw new IOException("Invalid length"); 1324 } 1325 bytesRead += 2; 1326 int read; 1327 while ((read = dataInputStream.read( 1328 bytes, 0, Math.min(length, bytes.length))) > 0) { 1329 length -= read; 1330 } 1331 bytesRead += length; 1332 writeExifSegment(dataOutputStream, bytesRead); 1333 break; 1334 } 1335 case MARKER_EOI: 1336 case MARKER_SOS: { 1337 // Copy all the remaining data 1338 Streams.copy(dataInputStream, dataOutputStream); 1339 return; 1340 } 1341 default: { 1342 // Copy JPEG segment 1343 int length = dataInputStream.readUnsignedShort(); 1344 dataOutputStream.writeUnsignedShort(length); 1345 if (length < 0) { 1346 throw new IOException("Invalid length"); 1347 } 1348 length -= 2; 1349 bytesRead += 2; 1350 int read; 1351 while ((read = dataInputStream.read( 1352 bytes, 0, Math.min(length, bytes.length))) > 0) { 1353 dataOutputStream.write(bytes, 0, read); 1354 length -= read; 1355 } 1356 bytesRead += length; 1357 break; 1358 } 1359 } 1360 } 1361 } 1362 1363 // Reads the given EXIF byte area and save its tag data into attributes. 1364 private void readExifSegment(byte[] exifBytes, int exifOffsetFromBeginning) throws IOException { 1365 // Parse TIFF Headers. See JEITA CP-3451C Table 1. page 10. 1366 ByteOrderAwarenessDataInputStream dataInputStream = 1367 new ByteOrderAwarenessDataInputStream(exifBytes); 1368 1369 // Read byte align 1370 short byteOrder = dataInputStream.readShort(); 1371 switch (byteOrder) { 1372 case BYTE_ALIGN_II: 1373 if (DEBUG) { 1374 Log.d(TAG, "readExifSegment: Byte Align II"); 1375 } 1376 dataInputStream.setByteOrder(ByteOrder.LITTLE_ENDIAN); 1377 break; 1378 case BYTE_ALIGN_MM: 1379 if (DEBUG) { 1380 Log.d(TAG, "readExifSegment: Byte Align MM"); 1381 } 1382 dataInputStream.setByteOrder(ByteOrder.BIG_ENDIAN); 1383 break; 1384 default: 1385 throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder)); 1386 } 1387 1388 int startCode = dataInputStream.readUnsignedShort(); 1389 if (startCode != 0x2a) { 1390 throw new IOException("Invalid exif start: " + Integer.toHexString(startCode)); 1391 } 1392 1393 // Read first ifd offset 1394 long firstIfdOffset = dataInputStream.readUnsignedInt(); 1395 if (firstIfdOffset < 8 || firstIfdOffset >= exifBytes.length) { 1396 throw new IOException("Invalid first Ifd offset: " + firstIfdOffset); 1397 } 1398 firstIfdOffset -= 8; 1399 if (firstIfdOffset > 0) { 1400 if (dataInputStream.skip(firstIfdOffset) != firstIfdOffset) { 1401 throw new IOException("Couldn't jump to first Ifd: " + firstIfdOffset); 1402 } 1403 } 1404 1405 // Read primary image TIFF image file directory. 1406 readImageFileDirectory(dataInputStream, IFD_TIFF_HINT); 1407 1408 // Process thumbnail. 1409 String jpegInterchangeFormatString = getAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name); 1410 String jpegInterchangeFormatLengthString = 1411 getAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name); 1412 if (jpegInterchangeFormatString != null && jpegInterchangeFormatLengthString != null) { 1413 try { 1414 int jpegInterchangeFormat = Integer.parseInt(jpegInterchangeFormatString); 1415 int jpegInterchangeFormatLength = Integer 1416 .parseInt(jpegInterchangeFormatLengthString); 1417 // The following code limits the size of thumbnail size not to overflow EXIF data area. 1418 jpegInterchangeFormatLength = Math.min(jpegInterchangeFormat 1419 + jpegInterchangeFormatLength, exifOffsetFromBeginning + exifBytes.length) 1420 - jpegInterchangeFormat; 1421 if (jpegInterchangeFormat > 0 && jpegInterchangeFormatLength > 0) { 1422 mHasThumbnail = true; 1423 mThumbnailOffset = exifOffsetFromBeginning + jpegInterchangeFormat; 1424 mThumbnailLength = jpegInterchangeFormatLength; 1425 1426 if (mFilename == null && mAssetInputStream == null 1427 && mSeekableFileDescriptor == null) { 1428 // Save the thumbnail in memory if the input doesn't support reading again. 1429 byte[] thumbnailBytes = new byte[jpegInterchangeFormatLength]; 1430 dataInputStream.seek(jpegInterchangeFormat); 1431 dataInputStream.readFully(thumbnailBytes); 1432 mThumbnailBytes = thumbnailBytes; 1433 1434 if (DEBUG) { 1435 Bitmap bitmap = BitmapFactory.decodeByteArray( 1436 thumbnailBytes, 0, thumbnailBytes.length); 1437 Log.d(TAG, "Thumbnail offset: " + mThumbnailOffset + ", length: " 1438 + mThumbnailLength + ", width: " + bitmap.getWidth() 1439 + ", height: " 1440 + bitmap.getHeight()); 1441 } 1442 } 1443 } 1444 } catch (NumberFormatException e) { 1445 // Ignored the corrupted image. 1446 } 1447 } 1448 1449 // For compatibility, keep data formats as follows. 1450 convertToInt(TAG_IMAGE_WIDTH); 1451 convertToInt(TAG_IMAGE_LENGTH); 1452 convertToInt(TAG_ORIENTATION); 1453 convertToInt(TAG_FLASH); 1454 convertToRational(TAG_FOCAL_LENGTH); 1455 convertToDouble(TAG_DIGITAL_ZOOM_RATIO); 1456 convertToDouble(TAG_EXPOSURE_TIME); 1457 convertToDouble(TAG_F_NUMBER); 1458 convertToDouble(TAG_SUBJECT_DISTANCE); 1459 convertToInt(TAG_ISO); 1460 convertToDouble(TAG_EXPOSURE_BIAS_VALUE); 1461 convertToInt(TAG_WHITE_BALANCE); 1462 convertToInt(TAG_LIGHT_SOURCE); 1463 convertToInt(TAG_METERING_MODE); 1464 convertToInt(TAG_EXPOSURE_PROGRAM); 1465 convertToInt(TAG_EXPOSURE_MODE); 1466 convertToRational(TAG_GPS_ALTITUDE); 1467 convertToInt(TAG_GPS_ALTITUDE_REF); 1468 convertToRational(TAG_GPS_LONGITUDE); 1469 convertToRational(TAG_GPS_LATITUDE); 1470 convertToTimetamp(TAG_GPS_TIMESTAMP); 1471 1472 // The value of DATETIME tag has the same value of DATETIME_ORIGINAL tag. 1473 String valueOfDateTimeOriginal = getAttribute("DateTimeOriginal"); 1474 if (valueOfDateTimeOriginal != null) { 1475 setAttribute(TAG_DATETIME, valueOfDateTimeOriginal); 1476 } 1477 1478 // Add the default value. 1479 if (getAttribute(TAG_IMAGE_WIDTH) == null) { 1480 setAttribute(TAG_IMAGE_WIDTH, "0"); 1481 } 1482 if (getAttribute(TAG_IMAGE_LENGTH) == null) { 1483 setAttribute(TAG_IMAGE_LENGTH, "0"); 1484 } 1485 if (getAttribute(TAG_ORIENTATION) == null) { 1486 setAttribute(TAG_ORIENTATION, "0"); 1487 } 1488 if (getAttribute(TAG_LIGHT_SOURCE) == null) { 1489 setAttribute(TAG_LIGHT_SOURCE, "0"); 1490 } 1491 } 1492 1493 // Converts the tag value to timestamp; Otherwise deletes the given tag. 1494 private void convertToTimetamp(String tagName) { 1495 String entryValue = getAttribute(tagName); 1496 if (entryValue == null) return; 1497 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 1498 String[] components = entryValue.split(","); 1499 if (dataFormat == IFD_FORMAT_SRATIONAL && components.length == 3) { 1500 StringBuilder stringBuilder = new StringBuilder(); 1501 for (String component : components) { 1502 if (stringBuilder.length() > 0) { 1503 stringBuilder.append(":"); 1504 } 1505 String[] rationalNumber = component.split("/"); 1506 int numerator = Integer.parseInt(rationalNumber[0]); 1507 int denominator = Integer.parseInt(rationalNumber[1]); 1508 if (denominator == 0) { 1509 numerator = 0; 1510 denominator = 1; 1511 } 1512 int value = numerator / denominator; 1513 stringBuilder.append(String.format("%02d", value)); 1514 } 1515 setAttribute(tagName, stringBuilder.toString()); 1516 } else if (dataFormat != IFD_FORMAT_STRING) { 1517 setAttribute(tagName, null); 1518 } 1519 } 1520 1521 // Checks the tag value of a given tag formatted in double type; Otherwise try to convert it to 1522 // double type or delete it. 1523 private void convertToDouble(String tagName) { 1524 String entryValue = getAttribute(tagName); 1525 if (entryValue == null) return; 1526 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 1527 switch (dataFormat) { 1528 case IFD_FORMAT_SRATIONAL: { 1529 StringBuilder stringBuilder = new StringBuilder(); 1530 String[] components = entryValue.split(","); 1531 for (String component : components) { 1532 if (stringBuilder.length() > 0) { 1533 stringBuilder.append(","); 1534 } 1535 String[] rationalNumber = component.split("/"); 1536 int numerator = Integer.parseInt(rationalNumber[0]); 1537 int denominator = Integer.parseInt(rationalNumber[1]); 1538 if (denominator == 0) { 1539 numerator = 0; 1540 denominator = 1; 1541 } 1542 stringBuilder.append((double) numerator / denominator); 1543 } 1544 setAttribute(tagName, stringBuilder.toString()); 1545 break; 1546 } 1547 case IFD_FORMAT_DOUBLE: 1548 // Keep it as is. 1549 break; 1550 default: 1551 setAttribute(tagName, null); 1552 break; 1553 } 1554 } 1555 1556 // Checks the tag value of a given tag formatted in int type; Otherwise deletes the tag value. 1557 private void convertToRational(String tagName) { 1558 String entryValue = getAttribute(tagName); 1559 if (entryValue == null) return; 1560 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 1561 switch (dataFormat) { 1562 case IFD_FORMAT_SLONG: 1563 case IFD_FORMAT_DOUBLE: { 1564 StringBuilder stringBuilder = new StringBuilder(); 1565 String[] components = entryValue.split(","); 1566 for (String component : components) { 1567 if (stringBuilder.length() > 0) { 1568 stringBuilder.append(","); 1569 } 1570 double doubleValue = Double.parseDouble(component); 1571 stringBuilder.append((int) (doubleValue * 10000.0)).append("/").append(10000); 1572 } 1573 setAttribute(tagName, stringBuilder.toString()); 1574 break; 1575 } 1576 case IFD_FORMAT_SRATIONAL: 1577 // Keep it as is. 1578 break; 1579 default: 1580 setAttribute(tagName, null); 1581 break; 1582 } 1583 } 1584 1585 // Checks the tag value of a given tag formatted in int type; Otherwise deletes the tag value. 1586 private void convertToInt(String tagName) { 1587 String entryValue = getAttribute(tagName); 1588 if (entryValue == null) return; 1589 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 1590 if (dataFormat != IFD_FORMAT_SLONG) { 1591 setAttribute(tagName, null); 1592 } 1593 } 1594 1595 // Reads image file directory, which is a tag group in EXIF. 1596 private void readImageFileDirectory(ByteOrderAwarenessDataInputStream dataInputStream, int hint) 1597 throws IOException { 1598 if (dataInputStream.peek() + 2 > dataInputStream.mLength) { 1599 // Return if there is no data from the offset. 1600 return; 1601 } 1602 // See JEITA CP-3451 Figure 5. page 9. 1603 short numberOfDirectoryEntry = dataInputStream.readShort(); 1604 if (dataInputStream.peek() + 12 * numberOfDirectoryEntry > dataInputStream.mLength) { 1605 // Return if the size of entries is too big. 1606 return; 1607 } 1608 1609 if (DEBUG) { 1610 Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry); 1611 } 1612 1613 for (short i = 0; i < numberOfDirectoryEntry; ++i) { 1614 int tagNumber = dataInputStream.readUnsignedShort(); 1615 int dataFormat = dataInputStream.readUnsignedShort(); 1616 int numberOfComponents = dataInputStream.readInt(); 1617 long nextEntryOffset = dataInputStream.peek() + 4; // next four bytes is for data 1618 // offset or value. 1619 // Look up a corresponding tag from tag number 1620 String tagName = (String) sExifTagMapsForReading[hint].get(tagNumber); 1621 1622 if (DEBUG) { 1623 Log.d(TAG, String.format("hint: %d, tagNumber: %d, tagName: %s, dataFormat: %d," + 1624 "numberOfComponents: %d", hint, tagNumber, tagName, dataFormat, 1625 numberOfComponents)); 1626 } 1627 1628 if (tagName == null || dataFormat <= 0 || 1629 dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) { 1630 // Skip if the parsed tag number is not defined or invalid data format. 1631 if (tagName == null) { 1632 Log.w(TAG, "Skip the tag entry since tag number is not defined: " + tagNumber); 1633 } else { 1634 Log.w(TAG, "Skip the tag entry since data format is invalid: " + dataFormat); 1635 } 1636 dataInputStream.seek(nextEntryOffset); 1637 continue; 1638 } 1639 1640 // Read a value from data field or seek to the value offset which is stored in data 1641 // field if the size of the entry value is bigger than 4. 1642 int byteCount = numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat]; 1643 if (byteCount > 4) { 1644 long offset = dataInputStream.readUnsignedInt(); 1645 if (DEBUG) { 1646 Log.d(TAG, "seek to data offset: " + offset); 1647 } 1648 if (offset + byteCount <= dataInputStream.mLength) { 1649 dataInputStream.seek(offset); 1650 } else { 1651 // Skip if invalid data offset. 1652 Log.w(TAG, "Skip the tag entry since data offset is invalid: " + offset); 1653 dataInputStream.seek(nextEntryOffset); 1654 continue; 1655 } 1656 } 1657 1658 // Recursively parse IFD when a IFD pointer tag appears. 1659 int innerIfdHint = getIfdHintFromTagNumber(tagNumber); 1660 if (DEBUG) { 1661 Log.d(TAG, "innerIfdHint: " + innerIfdHint + " byteCount: " + byteCount); 1662 } 1663 if (innerIfdHint >= 0) { 1664 long offset = -1L; 1665 // Get offset from data field 1666 switch (dataFormat) { 1667 case IFD_FORMAT_USHORT: { 1668 offset = dataInputStream.readUnsignedShort(); 1669 break; 1670 } 1671 case IFD_FORMAT_SSHORT: { 1672 offset = dataInputStream.readShort(); 1673 break; 1674 } 1675 case IFD_FORMAT_ULONG: { 1676 offset = dataInputStream.readUnsignedInt(); 1677 break; 1678 } 1679 case IFD_FORMAT_SLONG: { 1680 offset = dataInputStream.readInt(); 1681 break; 1682 } 1683 default: { 1684 // Nothing to do 1685 break; 1686 } 1687 } 1688 if (DEBUG) { 1689 Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tagName)); 1690 } 1691 if (offset > 0L && offset < dataInputStream.mLength) { 1692 dataInputStream.seek(offset); 1693 readImageFileDirectory(dataInputStream, innerIfdHint); 1694 } else { 1695 Log.w(TAG, "Skip jump into the IFD since its offset is invalid: " + offset); 1696 } 1697 1698 dataInputStream.seek(nextEntryOffset); 1699 continue; 1700 } 1701 1702 if (numberOfComponents == 1 || dataFormat == IFD_FORMAT_STRING 1703 || dataFormat == IFD_FORMAT_UNDEFINED) { 1704 String entryValue = readExifEntryValue( 1705 dataInputStream, dataFormat, numberOfComponents); 1706 if (entryValue != null) { 1707 setAttribute(tagName, entryValue); 1708 } 1709 } else { 1710 StringBuilder entryValueBuilder = new StringBuilder(); 1711 for (int c = 0; c < numberOfComponents; ++c) { 1712 if (entryValueBuilder.length() > 0) { 1713 entryValueBuilder.append(","); 1714 } 1715 entryValueBuilder.append(readExifEntryValue( 1716 dataInputStream, dataFormat, numberOfComponents)); 1717 } 1718 setAttribute(tagName, entryValueBuilder.toString()); 1719 } 1720 1721 if (dataInputStream.peek() != nextEntryOffset) { 1722 dataInputStream.seek(nextEntryOffset); 1723 } 1724 } 1725 1726 if (dataInputStream.peek() + 4 <= dataInputStream.mLength) { 1727 long nextIfdOffset = dataInputStream.readUnsignedInt(); 1728 if (DEBUG) { 1729 Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset)); 1730 } 1731 // The next IFD offset needs to be bigger than 8 1732 // since the first IFD offset is at least 8. 1733 if (nextIfdOffset > 8 && nextIfdOffset < dataInputStream.mLength) { 1734 dataInputStream.seek(nextIfdOffset); 1735 readImageFileDirectory(dataInputStream, IFD_THUMBNAIL_HINT); 1736 } 1737 } 1738 } 1739 1740 // Reads a value from where the entry value are stored. 1741 private String readExifEntryValue(ByteOrderAwarenessDataInputStream dataInputStream, 1742 int dataFormat, int numberOfComponents) throws IOException { 1743 // See TIFF 6.0 spec Types. page 15. 1744 switch (dataFormat) { 1745 case IFD_FORMAT_BYTE: { 1746 return String.valueOf(dataInputStream.readByte()); 1747 } 1748 case IFD_FORMAT_SBYTE: { 1749 return String.valueOf(dataInputStream.readByte() & 0xff); 1750 } 1751 case IFD_FORMAT_USHORT: { 1752 return String.valueOf(dataInputStream.readUnsignedShort()); 1753 } 1754 case IFD_FORMAT_SSHORT: { 1755 return String.valueOf(dataInputStream.readUnsignedInt()); 1756 } 1757 case IFD_FORMAT_ULONG: { 1758 return String.valueOf(dataInputStream.readInt()); 1759 } 1760 case IFD_FORMAT_SLONG: { 1761 return String.valueOf(dataInputStream.readInt()); 1762 } 1763 case IFD_FORMAT_URATIONAL: 1764 case IFD_FORMAT_SRATIONAL: { 1765 int numerator = dataInputStream.readInt(); 1766 int denominator = dataInputStream.readInt(); 1767 return numerator + "/" + denominator; 1768 } 1769 case IFD_FORMAT_SINGLE: { 1770 return String.valueOf(dataInputStream.readFloat()); 1771 } 1772 case IFD_FORMAT_DOUBLE: { 1773 return String.valueOf(dataInputStream.readDouble()); 1774 } 1775 case IFD_FORMAT_UNDEFINED: // Usually UNDEFINED format is ASCII. 1776 case IFD_FORMAT_STRING: { 1777 byte[] bytes = new byte[numberOfComponents]; 1778 dataInputStream.readFully(bytes); 1779 int index = 0; 1780 if (numberOfComponents >= EXIF_ASCII_PREFIX.length) { 1781 boolean same = true; 1782 for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) { 1783 if (bytes[i] != EXIF_ASCII_PREFIX[i]) { 1784 same = false; 1785 break; 1786 } 1787 } 1788 if (same) { 1789 index = EXIF_ASCII_PREFIX.length; 1790 } 1791 } 1792 1793 StringBuilder stringBuilder = new StringBuilder(); 1794 while (index < numberOfComponents) { 1795 int ch = bytes[index]; 1796 if (ch == 0) { 1797 break; 1798 } 1799 if (ch >= 32) { 1800 stringBuilder.append((char) ch); 1801 } 1802 else { 1803 stringBuilder.append('?'); 1804 } 1805 ++index; 1806 } 1807 return stringBuilder.toString(); 1808 } 1809 default: { 1810 // Nothing to do 1811 return null; 1812 } 1813 } 1814 } 1815 1816 // Gets the corresponding IFD group index of the given tag number for writing Exif Tags. 1817 private static int getIfdHintFromTagNumber(int tagNumber) { 1818 for (int i = 0; i < IFD_POINTER_TAG_HINTS.length; ++i) { 1819 if (IFD_POINTER_TAGS[i].number == tagNumber) { 1820 return IFD_POINTER_TAG_HINTS[i]; 1821 } 1822 } 1823 return -1; 1824 } 1825 1826 // Writes an Exif segment into the given output stream. 1827 private int writeExifSegment(ExifDataOutputStream dataOutputStream, int exifOffsetFromBeginning) 1828 throws IOException { 1829 // The following variables are for calculating each IFD tag group size in bytes. 1830 int[] ifdOffsets = new int[EXIF_TAGS.length]; 1831 int[] ifdDataSizes = new int[EXIF_TAGS.length]; 1832 1833 // Remove IFD pointer tags (we'll re-add it later.) 1834 for (ExifTag tag : IFD_POINTER_TAGS) { 1835 setAttribute(tag.name, null); 1836 } 1837 1838 // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD 1839 // offset when there is one or more tags in the thumbnail IFD. 1840 if (!mAttributes[IFD_INTEROPERABILITY_HINT].isEmpty()) { 1841 mAttributes[IFD_EXIF_HINT].put(IFD_POINTER_TAGS[2].name, "0"); 1842 } 1843 if (!mAttributes[IFD_EXIF_HINT].isEmpty()) { 1844 mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[0].name, "0"); 1845 } 1846 if (!mAttributes[IFD_GPS_HINT].isEmpty()) { 1847 mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[1].name, "0"); 1848 } 1849 // Remove old thumbnail data 1850 setAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name, null); 1851 setAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, null); 1852 if (mHasThumbnail) { 1853 mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_TAG.name, "0"); 1854 mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, 1855 String.valueOf(mThumbnailLength)); 1856 } 1857 1858 // Remove null value tags. 1859 for (int hint = 0; hint < EXIF_TAGS.length; ++hint) { 1860 for (Object obj : mAttributes[hint].entrySet().toArray()) { 1861 Map.Entry entry = (Map.Entry) obj; 1862 if (entry.getValue() == null) { 1863 mAttributes[hint].remove(entry.getKey()); 1864 } 1865 } 1866 } 1867 1868 // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry 1869 // value which has a bigger size than 4 bytes. 1870 for (int i = 0; i < 5; ++i) { 1871 int sum = 0; 1872 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[i].entrySet()) { 1873 String entryValue = (String) ((Map.Entry) entry).getValue(); 1874 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 1875 int size = getSizeOfExifEntryValue(dataFormat, entryValue); 1876 if (size > 4) { 1877 sum += size; 1878 } 1879 } 1880 ifdDataSizes[i] += sum; 1881 } 1882 1883 // Calculate IFD offsets. 1884 int position = 8; 1885 for (int hint = 0; hint < EXIF_TAGS.length; ++hint) { 1886 if (!mAttributes[hint].isEmpty()) { 1887 ifdOffsets[hint] = position; 1888 position += 2 + mAttributes[hint].size() * 12 + 4 + ifdDataSizes[hint]; 1889 } 1890 } 1891 if (mHasThumbnail) { 1892 int thumbnailOffset = position; 1893 mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_TAG.name, 1894 String.valueOf(thumbnailOffset)); 1895 mAttributes[IFD_TIFF_HINT].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, 1896 String.valueOf(mThumbnailLength)); 1897 mThumbnailOffset = exifOffsetFromBeginning + thumbnailOffset; 1898 position += mThumbnailLength; 1899 } 1900 1901 // Calculate the total size 1902 int totalSize = position + 8; // eight bytes is for header part. 1903 if (DEBUG) { 1904 Log.d(TAG, "totalSize length: " + totalSize); 1905 for (int i = 0; i < 5; ++i) { 1906 Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d", 1907 i, ifdOffsets[i], mAttributes[i].size(), ifdDataSizes[i])); 1908 } 1909 } 1910 1911 // Update IFD pointer tags with the calculated offsets. 1912 if (!mAttributes[IFD_EXIF_HINT].isEmpty()) { 1913 mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[0].name, 1914 String.valueOf(ifdOffsets[IFD_EXIF_HINT])); 1915 } 1916 if (!mAttributes[IFD_GPS_HINT].isEmpty()) { 1917 mAttributes[IFD_TIFF_HINT].put(IFD_POINTER_TAGS[1].name, 1918 String.valueOf(ifdOffsets[IFD_GPS_HINT])); 1919 } 1920 if (!mAttributes[IFD_INTEROPERABILITY_HINT].isEmpty()) { 1921 mAttributes[IFD_EXIF_HINT].put(IFD_POINTER_TAGS[2].name, 1922 String.valueOf(ifdOffsets[IFD_INTEROPERABILITY_HINT])); 1923 } 1924 1925 // Write TIFF Headers. See JEITA CP-3451C Table 1. page 10. 1926 dataOutputStream.writeUnsignedShort(totalSize); 1927 dataOutputStream.write(IDENTIFIER_APP1); 1928 dataOutputStream.writeShort(BYTE_ALIGN_MM); 1929 dataOutputStream.writeUnsignedShort(0x2a); 1930 dataOutputStream.writeUnsignedInt(8); 1931 1932 // Write IFD groups. See JEITA CP-3451C Figure 7. page 12. 1933 for (int hint = 0; hint < EXIF_TAGS.length; ++hint) { 1934 if (!mAttributes[hint].isEmpty()) { 1935 // See JEITA CP-3451C 4.6.2 IFD structure. page 13. 1936 // Write entry count 1937 dataOutputStream.writeUnsignedShort(mAttributes[hint].size()); 1938 1939 // Write entry info 1940 int dataOffset = ifdOffsets[hint] + 2 + mAttributes[hint].size() * 12 + 4; 1941 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[hint].entrySet()) { 1942 // Convert tag name to tag number. 1943 int tagNumber = (int) sExifTagMapsForWriting[hint].get(entry.getKey()); 1944 String entryValue = (String) entry.getValue(); 1945 1946 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 1947 int numberOfComponents = getNumberOfComponentsInExifEntryValue(dataFormat, 1948 entryValue); 1949 int byteCount = getSizeOfExifEntryValue(dataFormat, entryValue); 1950 1951 dataOutputStream.writeUnsignedShort(tagNumber); 1952 dataOutputStream.writeUnsignedShort(dataFormat); 1953 dataOutputStream.writeInt(numberOfComponents); 1954 if (byteCount > 4) { 1955 dataOutputStream.writeUnsignedInt(dataOffset); 1956 dataOffset += byteCount; 1957 } else { 1958 int bytesWritten = writeExifEntryValue(dataOutputStream, entryValue); 1959 // Fill zero up to 4 bytes 1960 if (bytesWritten < 4) { 1961 for (int i = bytesWritten; i < 4; ++i) { 1962 dataOutputStream.write(0); 1963 } 1964 } 1965 } 1966 } 1967 1968 // Write the next offset. It writes the offset of thumbnail IFD if there is one or 1969 // more tags in the thumbnail IFD when the current IFD is the primary image TIFF 1970 // IFD; Otherwise 0. 1971 if (hint == 0 && !mAttributes[IFD_THUMBNAIL_HINT].isEmpty()) { 1972 dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_THUMBNAIL_HINT]); 1973 } else { 1974 dataOutputStream.writeUnsignedInt(0); 1975 } 1976 1977 // Write values of data field exceeding 4 bytes after the next offset. 1978 for (Map.Entry entry : (Set<Map.Entry>) mAttributes[hint].entrySet()) { 1979 String entryValue = (String) entry.getValue(); 1980 1981 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 1982 int byteCount = getSizeOfExifEntryValue(dataFormat, entryValue); 1983 if (byteCount > 4) { 1984 writeExifEntryValue(dataOutputStream, entryValue); 1985 } 1986 } 1987 } 1988 } 1989 1990 // Write thumbnail 1991 if (mHasThumbnail) { 1992 dataOutputStream.write(getThumbnail()); 1993 } 1994 1995 return totalSize; 1996 } 1997 1998 // Writes EXIF entry value and its entry value type will be automatically determined. 1999 private static int writeExifEntryValue(ExifDataOutputStream dataOutputStream, String entryValue) 2000 throws IOException { 2001 int bytesWritten = 0; 2002 int dataFormat = getDataFormatOfExifEntryValue(entryValue); 2003 2004 // Values can be composed of several components. Each component is separated by char ','. 2005 String[] components = entryValue.split(","); 2006 for (String component : components) { 2007 switch (dataFormat) { 2008 case IFD_FORMAT_SLONG: 2009 dataOutputStream.writeInt(Integer.parseInt(component)); 2010 bytesWritten += 4; 2011 break; 2012 case IFD_FORMAT_DOUBLE: 2013 dataOutputStream.writeDouble(Double.parseDouble(component)); 2014 bytesWritten += 8; 2015 break; 2016 case IFD_FORMAT_STRING: 2017 byte[] asciiArray = (component + '\0').getBytes(Charset.forName("US-ASCII")); 2018 dataOutputStream.write(asciiArray); 2019 bytesWritten += asciiArray.length; 2020 break; 2021 case IFD_FORMAT_SRATIONAL: 2022 String[] rationalNumber = component.split("/"); 2023 dataOutputStream.writeInt(Integer.parseInt(rationalNumber[0])); 2024 dataOutputStream.writeInt(Integer.parseInt(rationalNumber[1])); 2025 bytesWritten += 8; 2026 break; 2027 default: 2028 throw new IllegalArgumentException(); 2029 } 2030 } 2031 return bytesWritten; 2032 } 2033 2034 // Determines the data format of EXIF entry value. 2035 private static int getDataFormatOfExifEntryValue(String entryValue) { 2036 // See TIFF 6.0 spec Types. page 15. 2037 // Take the first component if there are more than one component. 2038 if (entryValue.contains(",")) { 2039 entryValue = entryValue.split(",")[0]; 2040 } 2041 2042 if (entryValue.contains("/")) { 2043 return IFD_FORMAT_SRATIONAL; 2044 } 2045 try { 2046 Integer.parseInt(entryValue); 2047 return IFD_FORMAT_SLONG; 2048 } catch (NumberFormatException e) { 2049 // Ignored 2050 } 2051 try { 2052 Double.parseDouble(entryValue); 2053 return IFD_FORMAT_DOUBLE; 2054 } catch (NumberFormatException e) { 2055 // Ignored 2056 } 2057 return IFD_FORMAT_STRING; 2058 } 2059 2060 // Determines the size of EXIF entry value. 2061 private static int getSizeOfExifEntryValue(int dataFormat, String entryValue) { 2062 // See TIFF 6.0 spec Types page 15. 2063 int bytesEstimated = 0; 2064 String[] components = entryValue.split(","); 2065 for (String component : components) { 2066 switch (dataFormat) { 2067 case IFD_FORMAT_SLONG: 2068 bytesEstimated += 4; 2069 break; 2070 case IFD_FORMAT_DOUBLE: 2071 bytesEstimated += 8; 2072 break; 2073 case IFD_FORMAT_STRING: 2074 bytesEstimated 2075 += (component + '\0').getBytes(Charset.forName("US-ASCII")).length; 2076 break; 2077 case IFD_FORMAT_SRATIONAL: 2078 bytesEstimated += 8; 2079 break; 2080 default: 2081 throw new IllegalArgumentException(); 2082 } 2083 } 2084 return bytesEstimated; 2085 } 2086 2087 // Determines the number of components of EXIF entry value. 2088 private static int getNumberOfComponentsInExifEntryValue(int dataFormat, String entryValue) { 2089 if (dataFormat == IFD_FORMAT_STRING) { 2090 return (entryValue + '\0').getBytes(Charset.forName("US-ASCII")).length; 2091 } 2092 int count = 1; 2093 for (int i = 0; i < entryValue.length(); ++i) { 2094 if (entryValue.charAt(i) == ',') { 2095 ++count; 2096 } 2097 } 2098 return count; 2099 } 2100 2101 // An input stream to parse EXIF data area, which can be written in either little or big endian 2102 // order. 2103 private static class ByteOrderAwarenessDataInputStream extends ByteArrayInputStream { 2104 private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; 2105 private static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; 2106 2107 private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN; 2108 private final long mLength; 2109 private long mPosition; 2110 2111 public ByteOrderAwarenessDataInputStream(byte[] bytes) { 2112 super(bytes); 2113 mLength = bytes.length; 2114 mPosition = 0L; 2115 } 2116 2117 public void setByteOrder(ByteOrder byteOrder) { 2118 mByteOrder = byteOrder; 2119 } 2120 2121 public void seek(long byteCount) throws IOException { 2122 mPosition = 0L; 2123 reset(); 2124 if (skip(byteCount) != byteCount) { 2125 throw new IOException("Couldn't seek up to the byteCount"); 2126 } 2127 } 2128 2129 public long peek() { 2130 return mPosition; 2131 } 2132 2133 public void readFully(byte[] buffer) throws IOException { 2134 mPosition += buffer.length; 2135 if (mPosition > mLength) { 2136 throw new EOFException(); 2137 } 2138 if (super.read(buffer, 0, buffer.length) != buffer.length) { 2139 throw new IOException("Couldn't read up to the length of buffer"); 2140 } 2141 } 2142 2143 public byte readByte() throws IOException { 2144 ++mPosition; 2145 if (mPosition > mLength) { 2146 throw new EOFException(); 2147 } 2148 int ch = super.read(); 2149 if (ch < 0) { 2150 throw new EOFException(); 2151 } 2152 return (byte) ch; 2153 } 2154 2155 public short readShort() throws IOException { 2156 mPosition += 2; 2157 if (mPosition > mLength) { 2158 throw new EOFException(); 2159 } 2160 int ch1 = super.read(); 2161 int ch2 = super.read(); 2162 if ((ch1 | ch2) < 0) { 2163 throw new EOFException(); 2164 } 2165 if (mByteOrder == LITTLE_ENDIAN) { 2166 return (short) ((ch2 << 8) + (ch1)); 2167 } else if (mByteOrder == BIG_ENDIAN) { 2168 return (short) ((ch1 << 8) + (ch2)); 2169 } 2170 throw new IOException("Invalid byte order: " + mByteOrder); 2171 } 2172 2173 public int readInt() throws IOException { 2174 mPosition += 4; 2175 if (mPosition > mLength) { 2176 throw new EOFException(); 2177 } 2178 int ch1 = super.read(); 2179 int ch2 = super.read(); 2180 int ch3 = super.read(); 2181 int ch4 = super.read(); 2182 if ((ch1 | ch2 | ch3 | ch4) < 0) { 2183 throw new EOFException(); 2184 } 2185 if (mByteOrder == LITTLE_ENDIAN) { 2186 return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1); 2187 } else if (mByteOrder == BIG_ENDIAN) { 2188 return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4); 2189 } 2190 throw new IOException("Invalid byte order: " + mByteOrder); 2191 } 2192 2193 @Override 2194 public long skip(long byteCount) { 2195 long skipped = super.skip(Math.min(byteCount, mLength - mPosition)); 2196 mPosition += skipped; 2197 return skipped; 2198 } 2199 2200 public int readUnsignedShort() throws IOException { 2201 mPosition += 2; 2202 if (mPosition > mLength) { 2203 throw new EOFException(); 2204 } 2205 int ch1 = super.read(); 2206 int ch2 = super.read(); 2207 if ((ch1 | ch2) < 0) { 2208 throw new EOFException(); 2209 } 2210 if (mByteOrder == LITTLE_ENDIAN) { 2211 return ((ch2 << 8) + (ch1)); 2212 } else if (mByteOrder == BIG_ENDIAN) { 2213 return ((ch1 << 8) + (ch2)); 2214 } 2215 throw new IOException("Invalid byte order: " + mByteOrder); 2216 } 2217 2218 public long readUnsignedInt() throws IOException { 2219 return readInt() & 0xffffffffL; 2220 } 2221 2222 public long readLong() throws IOException { 2223 mPosition += 8; 2224 if (mPosition > mLength) { 2225 throw new EOFException(); 2226 } 2227 int ch1 = super.read(); 2228 int ch2 = super.read(); 2229 int ch3 = super.read(); 2230 int ch4 = super.read(); 2231 int ch5 = super.read(); 2232 int ch6 = super.read(); 2233 int ch7 = super.read(); 2234 int ch8 = super.read(); 2235 if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) { 2236 throw new EOFException(); 2237 } 2238 if (mByteOrder == LITTLE_ENDIAN) { 2239 return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40) 2240 + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16) 2241 + ((long) ch2 << 8) + (long) ch1); 2242 } else if (mByteOrder == BIG_ENDIAN) { 2243 return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40) 2244 + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16) 2245 + ((long) ch7 << 8) + (long) ch8); 2246 } 2247 throw new IOException("Invalid byte order: " + mByteOrder); 2248 } 2249 2250 public float readFloat() throws IOException { 2251 return Float.intBitsToFloat(readInt()); 2252 } 2253 2254 public double readDouble() throws IOException { 2255 return Double.longBitsToDouble(readLong()); 2256 } 2257 } 2258 2259 // An output stream to write EXIF data area, that will be written in big endian byte order. 2260 private static class ExifDataOutputStream extends DataOutputStream { 2261 public ExifDataOutputStream(OutputStream out) { 2262 super(out); 2263 } 2264 2265 public void writeUnsignedShort(int val) throws IOException { 2266 writeShort((short) val); 2267 } 2268 2269 public void writeUnsignedInt(long val) throws IOException { 2270 writeInt((int) val); 2271 } 2272 } 2273 2274 // JNI methods for RAW formats. 2275 private static native void nativeInitRaw(); 2276 private static native byte[] nativeGetThumbnailFromAsset( 2277 long asset, int thumbnailOffset, int thumbnailLength); 2278 private static native HashMap nativeGetRawAttributesFromAsset(long asset); 2279 private static native HashMap nativeGetRawAttributesFromFileDescriptor(FileDescriptor fd); 2280 private static native HashMap nativeGetRawAttributesFromInputStream(InputStream in); 2281} 2282