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