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