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