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.inBitmap != null && opts.inBitmap.getConfig() == Bitmap.Config.HARDWARE) { 437 throw new IllegalArgumentException("Bitmaps with Config.HARWARE are always immutable"); 438 } 439 440 if (opts.inMutable && opts.inPreferredConfig == Bitmap.Config.HARDWARE) { 441 throw new IllegalArgumentException("Bitmaps with Config.HARDWARE cannot be " + 442 "decoded into - they are immutable"); 443 } 444 445 if (opts.inPreferredColorSpace != null) { 446 if (!(opts.inPreferredColorSpace instanceof ColorSpace.Rgb)) { 447 throw new IllegalArgumentException("The destination color space must use the " + 448 "RGB color model"); 449 } 450 if (((ColorSpace.Rgb) opts.inPreferredColorSpace).getTransferParameters() == null) { 451 throw new IllegalArgumentException("The destination color space must use an " + 452 "ICC parametric transfer function"); 453 } 454 } 455 } 456 } 457 458 /** 459 * Decode a file path into a bitmap. If the specified file name is null, 460 * or cannot be decoded into a bitmap, the function returns null. 461 * 462 * @param pathName complete path name for the file to be decoded. 463 * @param opts null-ok; Options that control downsampling and whether the 464 * image should be completely decoded, or just is size returned. 465 * @return The decoded bitmap, or null if the image data could not be 466 * decoded, or, if opts is non-null, if opts requested only the 467 * size be returned (in opts.outWidth and opts.outHeight) 468 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 469 * is {@link android.graphics.Bitmap.Config#HARDWARE} 470 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 471 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 472 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 473 */ decodeFile(String pathName, Options opts)474 public static Bitmap decodeFile(String pathName, Options opts) { 475 validate(opts); 476 Bitmap bm = null; 477 InputStream stream = null; 478 try { 479 stream = new FileInputStream(pathName); 480 bm = decodeStream(stream, null, opts); 481 } catch (Exception e) { 482 /* do nothing. 483 If the exception happened on open, bm will be null. 484 */ 485 Log.e("BitmapFactory", "Unable to decode stream: " + e); 486 } finally { 487 if (stream != null) { 488 try { 489 stream.close(); 490 } catch (IOException e) { 491 // do nothing here 492 } 493 } 494 } 495 return bm; 496 } 497 498 /** 499 * Decode a file path into a bitmap. If the specified file name is null, 500 * or cannot be decoded into a bitmap, the function returns null. 501 * 502 * @param pathName complete path name for the file to be decoded. 503 * @return the resulting decoded bitmap, or null if it could not be decoded. 504 */ decodeFile(String pathName)505 public static Bitmap decodeFile(String pathName) { 506 return decodeFile(pathName, null); 507 } 508 509 /** 510 * Decode a new Bitmap from an InputStream. This InputStream was obtained from 511 * resources, which we pass to be able to scale the bitmap accordingly. 512 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 513 * is {@link android.graphics.Bitmap.Config#HARDWARE} 514 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 515 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 516 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 517 */ decodeResourceStream(Resources res, TypedValue value, InputStream is, Rect pad, Options opts)518 public static Bitmap decodeResourceStream(Resources res, TypedValue value, 519 InputStream is, Rect pad, Options opts) { 520 validate(opts); 521 if (opts == null) { 522 opts = new Options(); 523 } 524 525 if (opts.inDensity == 0 && value != null) { 526 final int density = value.density; 527 if (density == TypedValue.DENSITY_DEFAULT) { 528 opts.inDensity = DisplayMetrics.DENSITY_DEFAULT; 529 } else if (density != TypedValue.DENSITY_NONE) { 530 opts.inDensity = density; 531 } 532 } 533 534 if (opts.inTargetDensity == 0 && res != null) { 535 opts.inTargetDensity = res.getDisplayMetrics().densityDpi; 536 } 537 538 return decodeStream(is, pad, opts); 539 } 540 541 /** 542 * Synonym for opening the given resource and calling 543 * {@link #decodeResourceStream}. 544 * 545 * @param res The resources object containing the image data 546 * @param id The resource id of the image data 547 * @param opts null-ok; Options that control downsampling and whether the 548 * image should be completely decoded, or just is size returned. 549 * @return The decoded bitmap, or null if the image data could not be 550 * decoded, or, if opts is non-null, if opts requested only the 551 * size be returned (in opts.outWidth and opts.outHeight) 552 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 553 * is {@link android.graphics.Bitmap.Config#HARDWARE} 554 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 555 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 556 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 557 */ decodeResource(Resources res, int id, Options opts)558 public static Bitmap decodeResource(Resources res, int id, Options opts) { 559 validate(opts); 560 Bitmap bm = null; 561 InputStream is = null; 562 563 try { 564 final TypedValue value = new TypedValue(); 565 is = res.openRawResource(id, value); 566 567 bm = decodeResourceStream(res, value, is, null, opts); 568 } catch (Exception e) { 569 /* do nothing. 570 If the exception happened on open, bm will be null. 571 If it happened on close, bm is still valid. 572 */ 573 } finally { 574 try { 575 if (is != null) is.close(); 576 } catch (IOException e) { 577 // Ignore 578 } 579 } 580 581 if (bm == null && opts != null && opts.inBitmap != null) { 582 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 583 } 584 585 return bm; 586 } 587 588 /** 589 * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)} 590 * with null Options. 591 * 592 * @param res The resources object containing the image data 593 * @param id The resource id of the image data 594 * @return The decoded bitmap, or null if the image could not be decoded. 595 */ decodeResource(Resources res, int id)596 public static Bitmap decodeResource(Resources res, int id) { 597 return decodeResource(res, id, null); 598 } 599 600 /** 601 * Decode an immutable bitmap from the specified byte array. 602 * 603 * @param data byte array of compressed image data 604 * @param offset offset into imageData for where the decoder should begin 605 * parsing. 606 * @param length the number of bytes, beginning at offset, to parse 607 * @param opts null-ok; Options that control downsampling and whether the 608 * image should be completely decoded, or just is size returned. 609 * @return The decoded bitmap, or null if the image data could not be 610 * decoded, or, if opts is non-null, if opts requested only the 611 * size be returned (in opts.outWidth and opts.outHeight) 612 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 613 * is {@link android.graphics.Bitmap.Config#HARDWARE} 614 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 615 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 616 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 617 */ decodeByteArray(byte[] data, int offset, int length, Options opts)618 public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) { 619 if ((offset | length) < 0 || data.length < offset + length) { 620 throw new ArrayIndexOutOfBoundsException(); 621 } 622 validate(opts); 623 624 Bitmap bm; 625 626 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap"); 627 try { 628 bm = nativeDecodeByteArray(data, offset, length, opts); 629 630 if (bm == null && opts != null && opts.inBitmap != null) { 631 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 632 } 633 setDensityFromOptions(bm, opts); 634 } finally { 635 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 636 } 637 638 return bm; 639 } 640 641 /** 642 * Decode an immutable bitmap from the specified byte array. 643 * 644 * @param data byte array of compressed image data 645 * @param offset offset into imageData for where the decoder should begin 646 * parsing. 647 * @param length the number of bytes, beginning at offset, to parse 648 * @return The decoded bitmap, or null if the image could not be decoded. 649 */ decodeByteArray(byte[] data, int offset, int length)650 public static Bitmap decodeByteArray(byte[] data, int offset, int length) { 651 return decodeByteArray(data, offset, length, null); 652 } 653 654 /** 655 * Set the newly decoded bitmap's density based on the Options. 656 */ setDensityFromOptions(Bitmap outputBitmap, Options opts)657 private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) { 658 if (outputBitmap == null || opts == null) return; 659 660 final int density = opts.inDensity; 661 if (density != 0) { 662 outputBitmap.setDensity(density); 663 final int targetDensity = opts.inTargetDensity; 664 if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) { 665 return; 666 } 667 668 byte[] np = outputBitmap.getNinePatchChunk(); 669 final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np); 670 if (opts.inScaled || isNinePatch) { 671 outputBitmap.setDensity(targetDensity); 672 } 673 } else if (opts.inBitmap != null) { 674 // bitmap was reused, ensure density is reset 675 outputBitmap.setDensity(Bitmap.getDefaultDensity()); 676 } 677 } 678 679 /** 680 * Decode an input stream into a bitmap. If the input stream is null, or 681 * cannot be used to decode a bitmap, the function returns null. 682 * The stream's position will be where ever it was after the encoded data 683 * was read. 684 * 685 * @param is The input stream that holds the raw data to be decoded into a 686 * bitmap. 687 * @param outPadding If not null, return the padding rect for the bitmap if 688 * it exists, otherwise set padding to [-1,-1,-1,-1]. If 689 * no bitmap is returned (null) then padding is 690 * unchanged. 691 * @param opts null-ok; Options that control downsampling and whether the 692 * image should be completely decoded, or just is size returned. 693 * @return The decoded bitmap, or null if the image data could not be 694 * decoded, or, if opts is non-null, if opts requested only the 695 * size be returned (in opts.outWidth and opts.outHeight) 696 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 697 * is {@link android.graphics.Bitmap.Config#HARDWARE} 698 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 699 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 700 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 701 * 702 * <p class="note">Prior to {@link android.os.Build.VERSION_CODES#KITKAT}, 703 * if {@link InputStream#markSupported is.markSupported()} returns true, 704 * <code>is.mark(1024)</code> would be called. As of 705 * {@link android.os.Build.VERSION_CODES#KITKAT}, this is no longer the case.</p> 706 */ decodeStream(InputStream is, Rect outPadding, Options opts)707 public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) { 708 // we don't throw in this case, thus allowing the caller to only check 709 // the cache, and not force the image to be decoded. 710 if (is == null) { 711 return null; 712 } 713 validate(opts); 714 715 Bitmap bm = null; 716 717 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap"); 718 try { 719 if (is instanceof AssetManager.AssetInputStream) { 720 final long asset = ((AssetManager.AssetInputStream) is).getNativeAsset(); 721 bm = nativeDecodeAsset(asset, outPadding, opts); 722 } else { 723 bm = decodeStreamInternal(is, outPadding, opts); 724 } 725 726 if (bm == null && opts != null && opts.inBitmap != null) { 727 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 728 } 729 730 setDensityFromOptions(bm, opts); 731 } finally { 732 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 733 } 734 735 return bm; 736 } 737 738 /** 739 * Private helper function for decoding an InputStream natively. Buffers the input enough to 740 * do a rewind as needed, and supplies temporary storage if necessary. is MUST NOT be null. 741 */ decodeStreamInternal(InputStream is, Rect outPadding, Options opts)742 private static Bitmap decodeStreamInternal(InputStream is, Rect outPadding, Options opts) { 743 // ASSERT(is != null); 744 byte [] tempStorage = null; 745 if (opts != null) tempStorage = opts.inTempStorage; 746 if (tempStorage == null) tempStorage = new byte[DECODE_BUFFER_SIZE]; 747 return nativeDecodeStream(is, tempStorage, outPadding, opts); 748 } 749 750 /** 751 * Decode an input stream into a bitmap. If the input stream is null, or 752 * cannot be used to decode a bitmap, the function returns null. 753 * The stream's position will be where ever it was after the encoded data 754 * was read. 755 * 756 * @param is The input stream that holds the raw data to be decoded into a 757 * bitmap. 758 * @return The decoded bitmap, or null if the image data could not be decoded. 759 */ decodeStream(InputStream is)760 public static Bitmap decodeStream(InputStream is) { 761 return decodeStream(is, null, null); 762 } 763 764 /** 765 * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded 766 * return null. The position within the descriptor will not be changed when 767 * this returns, so the descriptor can be used again as-is. 768 * 769 * @param fd The file descriptor containing the bitmap data to decode 770 * @param outPadding If not null, return the padding rect for the bitmap if 771 * it exists, otherwise set padding to [-1,-1,-1,-1]. If 772 * no bitmap is returned (null) then padding is 773 * unchanged. 774 * @param opts null-ok; Options that control downsampling and whether the 775 * image should be completely decoded, or just its size returned. 776 * @return the decoded bitmap, or null 777 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 778 * is {@link android.graphics.Bitmap.Config#HARDWARE} 779 * and {@link BitmapFactory.Options#inMutable} is set, if the specified color space 780 * is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer 781 * function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve} 782 */ decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)783 public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) { 784 validate(opts); 785 Bitmap bm; 786 787 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeFileDescriptor"); 788 try { 789 if (nativeIsSeekable(fd)) { 790 bm = nativeDecodeFileDescriptor(fd, outPadding, opts); 791 } else { 792 FileInputStream fis = new FileInputStream(fd); 793 try { 794 bm = decodeStreamInternal(fis, outPadding, opts); 795 } finally { 796 try { 797 fis.close(); 798 } catch (Throwable t) {/* ignore */} 799 } 800 } 801 802 if (bm == null && opts != null && opts.inBitmap != null) { 803 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 804 } 805 806 setDensityFromOptions(bm, opts); 807 } finally { 808 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 809 } 810 return bm; 811 } 812 813 /** 814 * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded 815 * return null. The position within the descriptor will not be changed when 816 * this returns, so the descriptor can be used again as is. 817 * 818 * @param fd The file descriptor containing the bitmap data to decode 819 * @return the decoded bitmap, or null 820 */ decodeFileDescriptor(FileDescriptor fd)821 public static Bitmap decodeFileDescriptor(FileDescriptor fd) { 822 return decodeFileDescriptor(fd, null, null); 823 } 824 nativeDecodeStream(InputStream is, byte[] storage, Rect padding, Options opts)825 private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage, 826 Rect padding, Options opts); nativeDecodeFileDescriptor(FileDescriptor fd, Rect padding, Options opts)827 private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd, 828 Rect padding, Options opts); nativeDecodeAsset(long nativeAsset, Rect padding, Options opts)829 private static native Bitmap nativeDecodeAsset(long nativeAsset, Rect padding, Options opts); nativeDecodeByteArray(byte[] data, int offset, int length, Options opts)830 private static native Bitmap nativeDecodeByteArray(byte[] data, int offset, 831 int length, Options opts); nativeIsSeekable(FileDescriptor fd)832 private static native boolean nativeIsSeekable(FileDescriptor fd); 833 } 834