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 17 package android.graphics; 18 19 import static android.graphics.BitmapFactory.Options.validate; 20 21 import android.content.res.AssetManager; 22 import android.content.res.Resources; 23 import android.os.Trace; 24 import android.util.DisplayMetrics; 25 import android.util.Log; 26 import android.util.TypedValue; 27 28 import java.io.FileDescriptor; 29 import java.io.FileInputStream; 30 import java.io.IOException; 31 import java.io.InputStream; 32 33 /** 34 * Creates Bitmap objects from various sources, including files, streams, 35 * and byte-arrays. 36 */ 37 public class BitmapFactory { 38 private static final int DECODE_BUFFER_SIZE = 16 * 1024; 39 40 public static class Options { 41 /** 42 * Create a default Options object, which if left unchanged will give 43 * the same result from the decoder as if null were passed. 44 */ Options()45 public Options() { 46 inScaled = true; 47 inPremultiplied = true; 48 } 49 50 /** 51 * If set, decode methods that take the Options object will attempt to 52 * reuse this bitmap when loading content. If the decode operation 53 * cannot use this bitmap, the decode method will throw an 54 * {@link java.lang.IllegalArgumentException}. The 55 * current implementation necessitates that the reused bitmap be 56 * mutable, and the resulting reused bitmap will continue to remain 57 * mutable even when decoding a resource which would normally result in 58 * an immutable bitmap.</p> 59 * 60 * <p>You should still always use the returned Bitmap of the decode 61 * method and not assume that reusing the bitmap worked, due to the 62 * constraints outlined above and failure situations that can occur. 63 * Checking whether the return value matches the value of the inBitmap 64 * set in the Options structure will indicate if the bitmap was reused, 65 * but in all cases you should use the Bitmap returned by the decoding 66 * function to ensure that you are using the bitmap that was used as the 67 * decode destination.</p> 68 * 69 * <h3>Usage with BitmapFactory</h3> 70 * 71 * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, any 72 * mutable bitmap can be reused by {@link BitmapFactory} to decode any 73 * other bitmaps as long as the resulting {@link Bitmap#getByteCount() 74 * byte count} of the decoded bitmap is less than or equal to the {@link 75 * Bitmap#getAllocationByteCount() allocated byte count} of the reused 76 * bitmap. This can be because the intrinsic size is smaller, or its 77 * size post scaling (for density / sample size) is smaller.</p> 78 * 79 * <p class="note">Prior to {@link android.os.Build.VERSION_CODES#KITKAT} 80 * additional constraints apply: The image being decoded (whether as a 81 * resource or as a stream) must be in jpeg or png format. Only equal 82 * sized bitmaps are supported, with {@link #inSampleSize} set to 1. 83 * Additionally, the {@link android.graphics.Bitmap.Config 84 * configuration} of the reused bitmap will override the setting of 85 * {@link #inPreferredConfig}, if set.</p> 86 * 87 * <h3>Usage with BitmapRegionDecoder</h3> 88 * 89 * <p>BitmapRegionDecoder will draw its requested content into the Bitmap 90 * provided, clipping if the output content size (post scaling) is larger 91 * than the provided Bitmap. The provided Bitmap's width, height, and 92 * {@link Bitmap.Config} will not be changed. 93 * 94 * <p class="note">BitmapRegionDecoder support for {@link #inBitmap} was 95 * introduced in {@link android.os.Build.VERSION_CODES#JELLY_BEAN}. All 96 * formats supported by BitmapRegionDecoder support Bitmap reuse via 97 * {@link #inBitmap}.</p> 98 * 99 * @see Bitmap#reconfigure(int,int, android.graphics.Bitmap.Config) 100 */ 101 public Bitmap inBitmap; 102 103 /** 104 * If set, decode methods will always return a mutable Bitmap instead of 105 * an immutable one. This can be used for instance to programmatically apply 106 * effects to a Bitmap loaded through BitmapFactory. 107 * <p>Can not be set simultaneously with inPreferredConfig = 108 * {@link android.graphics.Bitmap.Config#HARDWARE}, 109 * because hardware bitmaps are always immutable. 110 */ 111 @SuppressWarnings({"UnusedDeclaration"}) // used in native code 112 public boolean inMutable; 113 114 /** 115 * If set to true, the decoder will return null (no bitmap), but 116 * the <code>out...</code> fields will still be set, allowing the caller to 117 * query the bitmap without having to allocate the memory for its pixels. 118 */ 119 public boolean inJustDecodeBounds; 120 121 /** 122 * If set to a value > 1, requests the decoder to subsample the original 123 * image, returning a smaller image to save memory. The sample size is 124 * the number of pixels in either dimension that correspond to a single 125 * pixel in the decoded bitmap. For example, inSampleSize == 4 returns 126 * an image that is 1/4 the width/height of the original, and 1/16 the 127 * number of pixels. Any value <= 1 is treated the same as 1. Note: the 128 * decoder uses a final value based on powers of 2, any other value will 129 * be rounded down to the nearest power of 2. 130 */ 131 public int inSampleSize; 132 133 /** 134 * If this is non-null, the decoder will try to decode into this 135 * internal configuration. If it is null, or the request cannot be met, 136 * the decoder will try to pick the best matching config based on the 137 * system's screen depth, and characteristics of the original image such 138 * as if it has per-pixel alpha (requiring a config that also does). 139 * 140 * Image are loaded with the {@link Bitmap.Config#ARGB_8888} config by 141 * default. 142 */ 143 public Bitmap.Config inPreferredConfig = Bitmap.Config.ARGB_8888; 144 145 /** 146 * <p>If this is non-null, the decoder will try to decode into this 147 * color space. If it is null, or the request cannot be met, 148 * the decoder will pick either the color space embedded in the image 149 * or the color space best suited for the requested image configuration 150 * (for instance {@link ColorSpace.Named#SRGB sRGB} for 151 * the {@link Bitmap.Config#ARGB_8888} configuration).</p> 152 * 153 * <p>{@link Bitmap.Config#RGBA_F16} always uses the 154 * {@link ColorSpace.Named#LINEAR_EXTENDED_SRGB scRGB} color space). 155 * Bitmaps in other configurations without an embedded color space are 156 * assumed to be in the {@link ColorSpace.Named#SRGB sRGB} color space.</p> 157 * 158 * <p class="note">Only {@link ColorSpace.Model#RGB} color spaces are 159 * currently supported. An <code>IllegalArgumentException</code> will 160 * be thrown by the decode methods when setting a non-RGB color space 161 * such as {@link ColorSpace.Named#CIE_LAB Lab}.</p> 162 * 163 * <p class="note">The specified color space's transfer function must be 164 * an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}. An 165 * <code>IllegalArgumentException</code> will be thrown by the decode methods 166 * if calling {@link ColorSpace.Rgb#getTransferParameters()} on the 167 * specified color space returns null.</p> 168 * 169 * <p>After decode, the bitmap's color space is stored in 170 * {@link #outColorSpace}.</p> 171 */ 172 public ColorSpace inPreferredColorSpace = null; 173 174 /** 175 * If true (which is the default), the resulting bitmap will have its 176 * color channels pre-multipled by the alpha channel. 177 * 178 * <p>This should NOT be set to false for images to be directly drawn by 179 * the view system or through a {@link Canvas}. The view system and 180 * {@link Canvas} assume all drawn images are pre-multiplied to simplify 181 * draw-time blending, and will throw a RuntimeException when 182 * un-premultiplied are drawn.</p> 183 * 184 * <p>This is likely only useful if you want to manipulate raw encoded 185 * image data, e.g. with RenderScript or custom OpenGL.</p> 186 * 187 * <p>This does not affect bitmaps without an alpha channel.</p> 188 * 189 * <p>Setting this flag to false while setting {@link #inScaled} to true 190 * may result in incorrect colors.</p> 191 * 192 * @see Bitmap#hasAlpha() 193 * @see Bitmap#isPremultiplied() 194 * @see #inScaled 195 */ 196 public boolean inPremultiplied; 197 198 /** 199 * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, this is 200 * ignored. 201 * 202 * In {@link android.os.Build.VERSION_CODES#M} and below, if dither is 203 * true, the decoder will attempt to dither the decoded image. 204 */ 205 public boolean inDither; 206 207 /** 208 * The pixel density to use for the bitmap. This will always result 209 * in the returned bitmap having a density set for it (see 210 * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}). In addition, 211 * if {@link #inScaled} is set (which it is by default} and this 212 * density does not match {@link #inTargetDensity}, then the bitmap 213 * will be scaled to the target density before being returned. 214 * 215 * <p>If this is 0, 216 * {@link BitmapFactory#decodeResource(Resources, int)}, 217 * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}, 218 * and {@link BitmapFactory#decodeResourceStream} 219 * will fill in the density associated with the resource. The other 220 * functions will leave it as-is and no density will be applied. 221 * 222 * @see #inTargetDensity 223 * @see #inScreenDensity 224 * @see #inScaled 225 * @see Bitmap#setDensity(int) 226 * @see android.util.DisplayMetrics#densityDpi 227 */ 228 public int inDensity; 229 230 /** 231 * The pixel density of the destination this bitmap will be drawn to. 232 * This is used in conjunction with {@link #inDensity} and 233 * {@link #inScaled} to determine if and how to scale the bitmap before 234 * returning it. 235 * 236 * <p>If this is 0, 237 * {@link BitmapFactory#decodeResource(Resources, int)}, 238 * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}, 239 * and {@link BitmapFactory#decodeResourceStream} 240 * will fill in the density associated the Resources object's 241 * DisplayMetrics. The other 242 * functions will leave it as-is and no scaling for density will be 243 * performed. 244 * 245 * @see #inDensity 246 * @see #inScreenDensity 247 * @see #inScaled 248 * @see android.util.DisplayMetrics#densityDpi 249 */ 250 public int inTargetDensity; 251 252 /** 253 * The pixel density of the actual screen that is being used. This is 254 * purely for applications running in density compatibility code, where 255 * {@link #inTargetDensity} is actually the density the application 256 * sees rather than the real screen density. 257 * 258 * <p>By setting this, you 259 * allow the loading code to avoid scaling a bitmap that is currently 260 * in the screen density up/down to the compatibility density. Instead, 261 * if {@link #inDensity} is the same as {@link #inScreenDensity}, the 262 * bitmap will be left as-is. Anything using the resulting bitmap 263 * must also used {@link Bitmap#getScaledWidth(int) 264 * Bitmap.getScaledWidth} and {@link Bitmap#getScaledHeight 265 * Bitmap.getScaledHeight} to account for any different between the 266 * bitmap's density and the target's density. 267 * 268 * <p>This is never set automatically for the caller by 269 * {@link BitmapFactory} itself. It must be explicitly set, since the 270 * caller must deal with the resulting bitmap in a density-aware way. 271 * 272 * @see #inDensity 273 * @see #inTargetDensity 274 * @see #inScaled 275 * @see android.util.DisplayMetrics#densityDpi 276 */ 277 public int inScreenDensity; 278 279 /** 280 * When this flag is set, if {@link #inDensity} and 281 * {@link #inTargetDensity} are not 0, the 282 * bitmap will be scaled to match {@link #inTargetDensity} when loaded, 283 * rather than relying on the graphics system scaling it each time it 284 * is drawn to a Canvas. 285 * 286 * <p>BitmapRegionDecoder ignores this flag, and will not scale output 287 * based on density. (though {@link #inSampleSize} is supported)</p> 288 * 289 * <p>This flag is turned on by default and should be turned off if you need 290 * a non-scaled version of the bitmap. Nine-patch bitmaps ignore this 291 * flag and are always scaled. 292 * 293 * <p>If {@link #inPremultiplied} is set to false, and the image has alpha, 294 * setting this flag to true may result in incorrect colors. 295 */ 296 public boolean inScaled; 297 298 /** 299 * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this is 300 * ignored. 301 * 302 * In {@link android.os.Build.VERSION_CODES#KITKAT} and below, if this 303 * is set to true, then the resulting bitmap will allocate its 304 * pixels such that they can be purged if the system needs to reclaim 305 * memory. In that instance, when the pixels need to be accessed again 306 * (e.g. the bitmap is drawn, getPixels() is called), they will be 307 * automatically re-decoded. 308 * 309 * <p>For the re-decode to happen, the bitmap must have access to the 310 * encoded data, either by sharing a reference to the input 311 * or by making a copy of it. This distinction is controlled by 312 * inInputShareable. If this is true, then the bitmap may keep a shallow 313 * reference to the input. If this is false, then the bitmap will 314 * explicitly make a copy of the input data, and keep that. Even if 315 * sharing is allowed, the implementation may still decide to make a 316 * deep copy of the input data.</p> 317 * 318 * <p>While inPurgeable can help avoid big Dalvik heap allocations (from 319 * API level 11 onward), it sacrifices performance predictability since any 320 * image that the view system tries to draw may incur a decode delay which 321 * can lead to dropped frames. Therefore, most apps should avoid using 322 * inPurgeable to allow for a fast and fluid UI. To minimize Dalvik heap 323 * allocations use the {@link #inBitmap} flag instead.</p> 324 * 325 * <p class="note"><strong>Note:</strong> This flag is ignored when used 326 * with {@link #decodeResource(Resources, int, 327 * android.graphics.BitmapFactory.Options)} or {@link #decodeFile(String, 328 * android.graphics.BitmapFactory.Options)}.</p> 329 */ 330 @Deprecated 331 public boolean inPurgeable; 332 333 /** 334 * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this is 335 * ignored. 336 * 337 * In {@link android.os.Build.VERSION_CODES#KITKAT} and below, this 338 * field works in conjuction with inPurgeable. If inPurgeable is false, 339 * then this field is ignored. If inPurgeable is true, then this field 340 * determines whether the bitmap can share a reference to the input 341 * data (inputstream, array, etc.) or if it must make a deep copy. 342 */ 343 @Deprecated 344 public boolean inInputShareable; 345 346 /** 347 * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, this is 348 * ignored. The output will always be high quality. 349 * 350 * In {@link android.os.Build.VERSION_CODES#M} and below, if 351 * inPreferQualityOverSpeed is set to true, the decoder will try to 352 * decode the reconstructed image to a higher quality even at the 353 * expense of the decoding speed. Currently the field only affects JPEG 354 * decode, in the case of which a more accurate, but slightly slower, 355 * IDCT method will be used instead. 356 */ 357 public boolean inPreferQualityOverSpeed; 358 359 /** 360 * The resulting width of the bitmap. If {@link #inJustDecodeBounds} is 361 * set to false, this will be width of the output bitmap after any 362 * scaling is applied. If true, it will be the width of the input image 363 * without any accounting for scaling. 364 * 365 * <p>outWidth will be set to -1 if there is an error trying to decode.</p> 366 */ 367 public int outWidth; 368 369 /** 370 * The resulting height of the bitmap. If {@link #inJustDecodeBounds} is 371 * set to false, this will be height of the output bitmap after any 372 * scaling is applied. If true, it will be the height of the input image 373 * without any accounting for scaling. 374 * 375 * <p>outHeight will be set to -1 if there is an error trying to decode.</p> 376 */ 377 public int outHeight; 378 379 /** 380 * If known, this string is set to the mimetype of the decoded image. 381 * If not known, or there is an error, it is set to null. 382 */ 383 public String outMimeType; 384 385 /** 386 * If known, the config the decoded bitmap will have. 387 * If not known, or there is an error, it is set to null. 388 */ 389 public Bitmap.Config outConfig; 390 391 /** 392 * If known, the color space the decoded bitmap will have. Note that the 393 * output color space is not guaranteed to be the color space the bitmap 394 * is encoded with. If not known (when the config is 395 * {@link Bitmap.Config#ALPHA_8} for instance), or there is an error, 396 * it is set to null. 397 */ 398 public ColorSpace outColorSpace; 399 400 /** 401 * Temp storage to use for decoding. Suggest 16K or so. 402 */ 403 public byte[] inTempStorage; 404 405 /** 406 * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, see 407 * comments on {@link #requestCancelDecode()}. 408 * 409 * Flag to indicate that cancel has been called on this object. This 410 * is useful if there's an intermediary that wants to first decode the 411 * bounds and then decode the image. In that case the intermediary 412 * can check, inbetween the bounds decode and the image decode, to see 413 * if the operation is canceled. 414 */ 415 public boolean mCancel; 416 417 /** 418 * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, this 419 * will not affect the decode, though it will still set mCancel. 420 * 421 * In {@link android.os.Build.VERSION_CODES#M} and below, if this can 422 * be called from another thread while this options object is inside 423 * a decode... call. Calling this will notify the decoder that it 424 * should cancel its operation. This is not guaranteed to cancel the 425 * decode, but if it does, the decoder... operation will return null, 426 * or if inJustDecodeBounds is true, will set outWidth/outHeight 427 * to -1 428 */ requestCancelDecode()429 public void requestCancelDecode() { 430 mCancel = true; 431 } 432 validate(Options opts)433 static void validate(Options opts) { 434 if (opts == null) return; 435 436 if (opts.inMutable && opts.inPreferredConfig == Bitmap.Config.HARDWARE) { 437 throw new IllegalArgumentException("Bitmaps with Config.HARWARE are always immutable"); 438 } 439 440 if (opts.inPreferredColorSpace != null) { 441 if (!(opts.inPreferredColorSpace instanceof ColorSpace.Rgb)) { 442 throw new IllegalArgumentException("The destination color space must use the " + 443 "RGB color model"); 444 } 445 if (((ColorSpace.Rgb) opts.inPreferredColorSpace).getTransferParameters() == null) { 446 throw new IllegalArgumentException("The destination color space must use an " + 447 "ICC parametric transfer function"); 448 } 449 } 450 } 451 } 452 453 /** 454 * Decode a file path into a bitmap. If the specified file name is null, 455 * or cannot be decoded into a bitmap, the function returns null. 456 * 457 * @param pathName complete path name for the file to be decoded. 458 * @param opts null-ok; Options that control downsampling and whether the 459 * image should be completely decoded, or just is size returned. 460 * @return The decoded bitmap, or null if the image data could not be 461 * decoded, or, if opts is non-null, if opts requested only the 462 * size be returned (in opts.outWidth and opts.outHeight) 463 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 464 * is {@link android.graphics.Bitmap.Config#HARDWARE} 465 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 466 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 467 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 468 */ decodeFile(String pathName, Options opts)469 public static Bitmap decodeFile(String pathName, Options opts) { 470 validate(opts); 471 Bitmap bm = null; 472 InputStream stream = null; 473 try { 474 stream = new FileInputStream(pathName); 475 bm = decodeStream(stream, null, opts); 476 } catch (Exception e) { 477 /* do nothing. 478 If the exception happened on open, bm will be null. 479 */ 480 Log.e("BitmapFactory", "Unable to decode stream: " + e); 481 } finally { 482 if (stream != null) { 483 try { 484 stream.close(); 485 } catch (IOException e) { 486 // do nothing here 487 } 488 } 489 } 490 return bm; 491 } 492 493 /** 494 * Decode a file path into a bitmap. If the specified file name is null, 495 * or cannot be decoded into a bitmap, the function returns null. 496 * 497 * @param pathName complete path name for the file to be decoded. 498 * @return the resulting decoded bitmap, or null if it could not be decoded. 499 */ decodeFile(String pathName)500 public static Bitmap decodeFile(String pathName) { 501 return decodeFile(pathName, null); 502 } 503 504 /** 505 * Decode a new Bitmap from an InputStream. This InputStream was obtained from 506 * resources, which we pass to be able to scale the bitmap accordingly. 507 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 508 * is {@link android.graphics.Bitmap.Config#HARDWARE} 509 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 510 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 511 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 512 */ decodeResourceStream(Resources res, TypedValue value, InputStream is, Rect pad, Options opts)513 public static Bitmap decodeResourceStream(Resources res, TypedValue value, 514 InputStream is, Rect pad, Options opts) { 515 validate(opts); 516 if (opts == null) { 517 opts = new Options(); 518 } 519 520 if (opts.inDensity == 0 && value != null) { 521 final int density = value.density; 522 if (density == TypedValue.DENSITY_DEFAULT) { 523 opts.inDensity = DisplayMetrics.DENSITY_DEFAULT; 524 } else if (density != TypedValue.DENSITY_NONE) { 525 opts.inDensity = density; 526 } 527 } 528 529 if (opts.inTargetDensity == 0 && res != null) { 530 opts.inTargetDensity = res.getDisplayMetrics().densityDpi; 531 } 532 533 return decodeStream(is, pad, opts); 534 } 535 536 /** 537 * Synonym for opening the given resource and calling 538 * {@link #decodeResourceStream}. 539 * 540 * @param res The resources object containing the image data 541 * @param id The resource id of the image data 542 * @param opts null-ok; Options that control downsampling and whether the 543 * image should be completely decoded, or just is size returned. 544 * @return The decoded bitmap, or null if the image data could not be 545 * decoded, or, if opts is non-null, if opts requested only the 546 * size be returned (in opts.outWidth and opts.outHeight) 547 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 548 * is {@link android.graphics.Bitmap.Config#HARDWARE} 549 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 550 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 551 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 552 */ decodeResource(Resources res, int id, Options opts)553 public static Bitmap decodeResource(Resources res, int id, Options opts) { 554 validate(opts); 555 Bitmap bm = null; 556 InputStream is = null; 557 558 try { 559 final TypedValue value = new TypedValue(); 560 is = res.openRawResource(id, value); 561 562 bm = decodeResourceStream(res, value, is, null, opts); 563 } catch (Exception e) { 564 /* do nothing. 565 If the exception happened on open, bm will be null. 566 If it happened on close, bm is still valid. 567 */ 568 } finally { 569 try { 570 if (is != null) is.close(); 571 } catch (IOException e) { 572 // Ignore 573 } 574 } 575 576 if (bm == null && opts != null && opts.inBitmap != null) { 577 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 578 } 579 580 return bm; 581 } 582 583 /** 584 * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)} 585 * with null Options. 586 * 587 * @param res The resources object containing the image data 588 * @param id The resource id of the image data 589 * @return The decoded bitmap, or null if the image could not be decoded. 590 */ decodeResource(Resources res, int id)591 public static Bitmap decodeResource(Resources res, int id) { 592 return decodeResource(res, id, null); 593 } 594 595 /** 596 * Decode an immutable bitmap from the specified byte array. 597 * 598 * @param data byte array of compressed image data 599 * @param offset offset into imageData for where the decoder should begin 600 * parsing. 601 * @param length the number of bytes, beginning at offset, to parse 602 * @param opts null-ok; Options that control downsampling and whether the 603 * image should be completely decoded, or just is size returned. 604 * @return The decoded bitmap, or null if the image data could not be 605 * decoded, or, if opts is non-null, if opts requested only the 606 * size be returned (in opts.outWidth and opts.outHeight) 607 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 608 * is {@link android.graphics.Bitmap.Config#HARDWARE} 609 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 610 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 611 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 612 */ decodeByteArray(byte[] data, int offset, int length, Options opts)613 public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) { 614 if ((offset | length) < 0 || data.length < offset + length) { 615 throw new ArrayIndexOutOfBoundsException(); 616 } 617 validate(opts); 618 619 Bitmap bm; 620 621 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap"); 622 try { 623 bm = nativeDecodeByteArray(data, offset, length, opts); 624 625 if (bm == null && opts != null && opts.inBitmap != null) { 626 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 627 } 628 setDensityFromOptions(bm, opts); 629 } finally { 630 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 631 } 632 633 return bm; 634 } 635 636 /** 637 * Decode an immutable bitmap from the specified byte array. 638 * 639 * @param data byte array of compressed image data 640 * @param offset offset into imageData for where the decoder should begin 641 * parsing. 642 * @param length the number of bytes, beginning at offset, to parse 643 * @return The decoded bitmap, or null if the image could not be decoded. 644 */ decodeByteArray(byte[] data, int offset, int length)645 public static Bitmap decodeByteArray(byte[] data, int offset, int length) { 646 return decodeByteArray(data, offset, length, null); 647 } 648 649 /** 650 * Set the newly decoded bitmap's density based on the Options. 651 */ setDensityFromOptions(Bitmap outputBitmap, Options opts)652 private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) { 653 if (outputBitmap == null || opts == null) return; 654 655 final int density = opts.inDensity; 656 if (density != 0) { 657 outputBitmap.setDensity(density); 658 final int targetDensity = opts.inTargetDensity; 659 if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) { 660 return; 661 } 662 663 byte[] np = outputBitmap.getNinePatchChunk(); 664 final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np); 665 if (opts.inScaled || isNinePatch) { 666 outputBitmap.setDensity(targetDensity); 667 } 668 } else if (opts.inBitmap != null) { 669 // bitmap was reused, ensure density is reset 670 outputBitmap.setDensity(Bitmap.getDefaultDensity()); 671 } 672 } 673 674 /** 675 * Decode an input stream into a bitmap. If the input stream is null, or 676 * cannot be used to decode a bitmap, the function returns null. 677 * The stream's position will be where ever it was after the encoded data 678 * was read. 679 * 680 * @param is The input stream that holds the raw data to be decoded into a 681 * bitmap. 682 * @param outPadding If not null, return the padding rect for the bitmap if 683 * it exists, otherwise set padding to [-1,-1,-1,-1]. If 684 * no bitmap is returned (null) then padding is 685 * unchanged. 686 * @param opts null-ok; Options that control downsampling and whether the 687 * image should be completely decoded, or just is size returned. 688 * @return The decoded bitmap, or null if the image data could not be 689 * decoded, or, if opts is non-null, if opts requested only the 690 * size be returned (in opts.outWidth and opts.outHeight) 691 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 692 * is {@link android.graphics.Bitmap.Config#HARDWARE} 693 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 694 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 695 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 696 * 697 * <p class="note">Prior to {@link android.os.Build.VERSION_CODES#KITKAT}, 698 * if {@link InputStream#markSupported is.markSupported()} returns true, 699 * <code>is.mark(1024)</code> would be called. As of 700 * {@link android.os.Build.VERSION_CODES#KITKAT}, this is no longer the case.</p> 701 */ decodeStream(InputStream is, Rect outPadding, Options opts)702 public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) { 703 // we don't throw in this case, thus allowing the caller to only check 704 // the cache, and not force the image to be decoded. 705 if (is == null) { 706 return null; 707 } 708 validate(opts); 709 710 Bitmap bm = null; 711 712 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap"); 713 try { 714 if (is instanceof AssetManager.AssetInputStream) { 715 final long asset = ((AssetManager.AssetInputStream) is).getNativeAsset(); 716 bm = nativeDecodeAsset(asset, outPadding, opts); 717 } else { 718 bm = decodeStreamInternal(is, outPadding, opts); 719 } 720 721 if (bm == null && opts != null && opts.inBitmap != null) { 722 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 723 } 724 725 setDensityFromOptions(bm, opts); 726 } finally { 727 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 728 } 729 730 return bm; 731 } 732 733 /** 734 * Private helper function for decoding an InputStream natively. Buffers the input enough to 735 * do a rewind as needed, and supplies temporary storage if necessary. is MUST NOT be null. 736 */ decodeStreamInternal(InputStream is, Rect outPadding, Options opts)737 private static Bitmap decodeStreamInternal(InputStream is, Rect outPadding, Options opts) { 738 // ASSERT(is != null); 739 byte [] tempStorage = null; 740 if (opts != null) tempStorage = opts.inTempStorage; 741 if (tempStorage == null) tempStorage = new byte[DECODE_BUFFER_SIZE]; 742 return nativeDecodeStream(is, tempStorage, outPadding, opts); 743 } 744 745 /** 746 * Decode an input stream into a bitmap. If the input stream is null, or 747 * cannot be used to decode a bitmap, the function returns null. 748 * The stream's position will be where ever it was after the encoded data 749 * was read. 750 * 751 * @param is The input stream that holds the raw data to be decoded into a 752 * bitmap. 753 * @return The decoded bitmap, or null if the image data could not be decoded. 754 */ decodeStream(InputStream is)755 public static Bitmap decodeStream(InputStream is) { 756 return decodeStream(is, null, null); 757 } 758 759 /** 760 * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded 761 * return null. The position within the descriptor will not be changed when 762 * this returns, so the descriptor can be used again as-is. 763 * 764 * @param fd The file descriptor containing the bitmap data to decode 765 * @param outPadding If not null, return the padding rect for the bitmap if 766 * it exists, otherwise set padding to [-1,-1,-1,-1]. If 767 * no bitmap is returned (null) then padding is 768 * unchanged. 769 * @param opts null-ok; Options that control downsampling and whether the 770 * image should be completely decoded, or just its size returned. 771 * @return the decoded bitmap, or null 772 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 773 * is {@link android.graphics.Bitmap.Config#HARDWARE} 774 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 775 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 776 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 777 */ decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)778 public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) { 779 validate(opts); 780 Bitmap bm; 781 782 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeFileDescriptor"); 783 try { 784 if (nativeIsSeekable(fd)) { 785 bm = nativeDecodeFileDescriptor(fd, outPadding, opts); 786 } else { 787 FileInputStream fis = new FileInputStream(fd); 788 try { 789 bm = decodeStreamInternal(fis, outPadding, opts); 790 } finally { 791 try { 792 fis.close(); 793 } catch (Throwable t) {/* ignore */} 794 } 795 } 796 797 if (bm == null && opts != null && opts.inBitmap != null) { 798 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 799 } 800 801 setDensityFromOptions(bm, opts); 802 } finally { 803 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 804 } 805 return bm; 806 } 807 808 /** 809 * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded 810 * return null. The position within the descriptor will not be changed when 811 * this returns, so the descriptor can be used again as is. 812 * 813 * @param fd The file descriptor containing the bitmap data to decode 814 * @return the decoded bitmap, or null 815 */ decodeFileDescriptor(FileDescriptor fd)816 public static Bitmap decodeFileDescriptor(FileDescriptor fd) { 817 return decodeFileDescriptor(fd, null, null); 818 } 819 nativeDecodeStream(InputStream is, byte[] storage, Rect padding, Options opts)820 private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage, 821 Rect padding, Options opts); nativeDecodeFileDescriptor(FileDescriptor fd, Rect padding, Options opts)822 private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd, 823 Rect padding, Options opts); nativeDecodeAsset(long nativeAsset, Rect padding, Options opts)824 private static native Bitmap nativeDecodeAsset(long nativeAsset, Rect padding, Options opts); nativeDecodeByteArray(byte[] data, int offset, int length, Options opts)825 private static native Bitmap nativeDecodeByteArray(byte[] data, int offset, 826 int length, Options opts); nativeIsSeekable(FileDescriptor fd)827 private static native boolean nativeIsSeekable(FileDescriptor fd); 828 } 829