BitmapFactory.java revision 9fbb0b5ab321d86efbc7fa8774052bfb34de9557
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 return 55 * <code>null</code> and will throw an 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 know, or there is an error, it is set to null. 354 */ 355 public String outMimeType; 356 357 /** 358 * Temp storage to use for decoding. Suggest 16K or so. 359 */ 360 public byte[] inTempStorage; 361 362 /** 363 * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, see 364 * comments on {@link #requestCancelDecode()}. 365 * 366 * Flag to indicate that cancel has been called on this object. This 367 * is useful if there's an intermediary that wants to first decode the 368 * bounds and then decode the image. In that case the intermediary 369 * can check, inbetween the bounds decode and the image decode, to see 370 * if the operation is canceled. 371 */ 372 public boolean mCancel; 373 374 /** 375 * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, this 376 * will not affect the decode, though it will still set mCancel. 377 * 378 * In {@link android.os.Build.VERSION_CODES#M} and below, if this can 379 * be called from another thread while this options object is inside 380 * a decode... call. Calling this will notify the decoder that it 381 * should cancel its operation. This is not guaranteed to cancel the 382 * decode, but if it does, the decoder... operation will return null, 383 * or if inJustDecodeBounds is true, will set outWidth/outHeight 384 * to -1 385 */ 386 public void requestCancelDecode() { 387 mCancel = true; 388 } 389 390 static void validate(Options opts) { 391 if (opts != null && opts.inMutable && opts.inPreferredConfig == Bitmap.Config.HARDWARE) { 392 throw new IllegalArgumentException("Bitmaps with Config.HARWARE are always immutable"); 393 } 394 } 395 } 396 397 /** 398 * Decode a file path into a bitmap. If the specified file name is null, 399 * or cannot be decoded into a bitmap, the function returns null. 400 * 401 * @param pathName complete path name for the file to be decoded. 402 * @param opts null-ok; Options that control downsampling and whether the 403 * image should be completely decoded, or just is size returned. 404 * @return The decoded bitmap, or null if the image data could not be 405 * decoded, or, if opts is non-null, if opts requested only the 406 * size be returned (in opts.outWidth and opts.outHeight) 407 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 408 * is {@link android.graphics.Bitmap.Config#HARDWARE} 409 * and {@link BitmapFactory.Options#inMutable} is set. 410 */ 411 public static Bitmap decodeFile(String pathName, Options opts) { 412 validate(opts); 413 Bitmap bm = null; 414 InputStream stream = null; 415 try { 416 stream = new FileInputStream(pathName); 417 bm = decodeStream(stream, null, opts); 418 } catch (Exception e) { 419 /* do nothing. 420 If the exception happened on open, bm will be null. 421 */ 422 Log.e("BitmapFactory", "Unable to decode stream: " + e); 423 } finally { 424 if (stream != null) { 425 try { 426 stream.close(); 427 } catch (IOException e) { 428 // do nothing here 429 } 430 } 431 } 432 return bm; 433 } 434 435 /** 436 * Decode a file path into a bitmap. If the specified file name is null, 437 * or cannot be decoded into a bitmap, the function returns null. 438 * 439 * @param pathName complete path name for the file to be decoded. 440 * @return the resulting decoded bitmap, or null if it could not be decoded. 441 */ 442 public static Bitmap decodeFile(String pathName) { 443 return decodeFile(pathName, null); 444 } 445 446 /** 447 * Decode a new Bitmap from an InputStream. This InputStream was obtained from 448 * resources, which we pass to be able to scale the bitmap accordingly. 449 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 450 * is {@link android.graphics.Bitmap.Config#HARDWARE} 451 * and {@link BitmapFactory.Options#inMutable} is set. 452 */ 453 public static Bitmap decodeResourceStream(Resources res, TypedValue value, 454 InputStream is, Rect pad, Options opts) { 455 validate(opts); 456 if (opts == null) { 457 opts = new Options(); 458 } 459 460 if (opts.inDensity == 0 && value != null) { 461 final int density = value.density; 462 if (density == TypedValue.DENSITY_DEFAULT) { 463 opts.inDensity = DisplayMetrics.DENSITY_DEFAULT; 464 } else if (density != TypedValue.DENSITY_NONE) { 465 opts.inDensity = density; 466 } 467 } 468 469 if (opts.inTargetDensity == 0 && res != null) { 470 opts.inTargetDensity = res.getDisplayMetrics().densityDpi; 471 } 472 473 return decodeStream(is, pad, opts); 474 } 475 476 /** 477 * Synonym for opening the given resource and calling 478 * {@link #decodeResourceStream}. 479 * 480 * @param res The resources object containing the image data 481 * @param id The resource id of the image data 482 * @param opts null-ok; Options that control downsampling and whether the 483 * image should be completely decoded, or just is size returned. 484 * @return The decoded bitmap, or null if the image data could not be 485 * decoded, or, if opts is non-null, if opts requested only the 486 * size be returned (in opts.outWidth and opts.outHeight) 487 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 488 * is {@link android.graphics.Bitmap.Config#HARDWARE} 489 * and {@link BitmapFactory.Options#inMutable} is set. 490 */ 491 public static Bitmap decodeResource(Resources res, int id, Options opts) { 492 validate(opts); 493 Bitmap bm = null; 494 InputStream is = null; 495 496 try { 497 final TypedValue value = new TypedValue(); 498 is = res.openRawResource(id, value); 499 500 bm = decodeResourceStream(res, value, is, null, opts); 501 } catch (Exception e) { 502 /* do nothing. 503 If the exception happened on open, bm will be null. 504 If it happened on close, bm is still valid. 505 */ 506 } finally { 507 try { 508 if (is != null) is.close(); 509 } catch (IOException e) { 510 // Ignore 511 } 512 } 513 514 if (bm == null && opts != null && opts.inBitmap != null) { 515 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 516 } 517 518 return bm; 519 } 520 521 /** 522 * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)} 523 * with null Options. 524 * 525 * @param res The resources object containing the image data 526 * @param id The resource id of the image data 527 * @return The decoded bitmap, or null if the image could not be decoded. 528 */ 529 public static Bitmap decodeResource(Resources res, int id) { 530 return decodeResource(res, id, null); 531 } 532 533 /** 534 * Decode an immutable bitmap from the specified byte array. 535 * 536 * @param data byte array of compressed image data 537 * @param offset offset into imageData for where the decoder should begin 538 * parsing. 539 * @param length the number of bytes, beginning at offset, to parse 540 * @param opts null-ok; Options that control downsampling and whether the 541 * image should be completely decoded, or just is size returned. 542 * @return The decoded bitmap, or null if the image data could not be 543 * decoded, or, if opts is non-null, if opts requested only the 544 * size be returned (in opts.outWidth and opts.outHeight) 545 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 546 * is {@link android.graphics.Bitmap.Config#HARDWARE} 547 * and {@link BitmapFactory.Options#inMutable} is set. 548 */ 549 public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) { 550 if ((offset | length) < 0 || data.length < offset + length) { 551 throw new ArrayIndexOutOfBoundsException(); 552 } 553 validate(opts); 554 555 Bitmap bm; 556 557 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap"); 558 try { 559 bm = nativeDecodeByteArray(data, offset, length, opts); 560 561 if (bm == null && opts != null && opts.inBitmap != null) { 562 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 563 } 564 setDensityFromOptions(bm, opts); 565 } finally { 566 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 567 } 568 569 return bm; 570 } 571 572 /** 573 * Decode an immutable bitmap from the specified byte array. 574 * 575 * @param data byte array of compressed image data 576 * @param offset offset into imageData for where the decoder should begin 577 * parsing. 578 * @param length the number of bytes, beginning at offset, to parse 579 * @return The decoded bitmap, or null if the image could not be decoded. 580 */ 581 public static Bitmap decodeByteArray(byte[] data, int offset, int length) { 582 return decodeByteArray(data, offset, length, null); 583 } 584 585 /** 586 * Set the newly decoded bitmap's density based on the Options. 587 */ 588 private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) { 589 if (outputBitmap == null || opts == null) return; 590 591 final int density = opts.inDensity; 592 if (density != 0) { 593 outputBitmap.setDensity(density); 594 final int targetDensity = opts.inTargetDensity; 595 if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) { 596 return; 597 } 598 599 byte[] np = outputBitmap.getNinePatchChunk(); 600 final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np); 601 if (opts.inScaled || isNinePatch) { 602 outputBitmap.setDensity(targetDensity); 603 } 604 } else if (opts.inBitmap != null) { 605 // bitmap was reused, ensure density is reset 606 outputBitmap.setDensity(Bitmap.getDefaultDensity()); 607 } 608 } 609 610 /** 611 * Decode an input stream into a bitmap. If the input stream is null, or 612 * cannot be used to decode a bitmap, the function returns null. 613 * The stream's position will be where ever it was after the encoded data 614 * was read. 615 * 616 * @param is The input stream that holds the raw data to be decoded into a 617 * bitmap. 618 * @param outPadding If not null, return the padding rect for the bitmap if 619 * it exists, otherwise set padding to [-1,-1,-1,-1]. If 620 * no bitmap is returned (null) then padding is 621 * unchanged. 622 * @param opts null-ok; Options that control downsampling and whether the 623 * image should be completely decoded, or just is size returned. 624 * @return The decoded bitmap, or null if the image data could not be 625 * decoded, or, if opts is non-null, if opts requested only the 626 * size be returned (in opts.outWidth and opts.outHeight) 627 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 628 * is {@link android.graphics.Bitmap.Config#HARDWARE} 629 * and {@link BitmapFactory.Options#inMutable} is set. 630 * 631 * <p class="note">Prior to {@link android.os.Build.VERSION_CODES#KITKAT}, 632 * if {@link InputStream#markSupported is.markSupported()} returns true, 633 * <code>is.mark(1024)</code> would be called. As of 634 * {@link android.os.Build.VERSION_CODES#KITKAT}, this is no longer the case.</p> 635 */ 636 public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) { 637 // we don't throw in this case, thus allowing the caller to only check 638 // the cache, and not force the image to be decoded. 639 if (is == null) { 640 return null; 641 } 642 validate(opts); 643 644 Bitmap bm = null; 645 646 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap"); 647 try { 648 if (is instanceof AssetManager.AssetInputStream) { 649 final long asset = ((AssetManager.AssetInputStream) is).getNativeAsset(); 650 bm = nativeDecodeAsset(asset, outPadding, opts); 651 } else { 652 bm = decodeStreamInternal(is, outPadding, opts); 653 } 654 655 if (bm == null && opts != null && opts.inBitmap != null) { 656 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 657 } 658 659 setDensityFromOptions(bm, opts); 660 } finally { 661 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 662 } 663 664 return bm; 665 } 666 667 /** 668 * Private helper function for decoding an InputStream natively. Buffers the input enough to 669 * do a rewind as needed, and supplies temporary storage if necessary. is MUST NOT be null. 670 */ 671 private static Bitmap decodeStreamInternal(InputStream is, Rect outPadding, Options opts) { 672 // ASSERT(is != null); 673 byte [] tempStorage = null; 674 if (opts != null) tempStorage = opts.inTempStorage; 675 if (tempStorage == null) tempStorage = new byte[DECODE_BUFFER_SIZE]; 676 return nativeDecodeStream(is, tempStorage, outPadding, opts); 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 * @return The decoded bitmap, or null if the image data could not be decoded. 688 */ 689 public static Bitmap decodeStream(InputStream is) { 690 return decodeStream(is, null, null); 691 } 692 693 /** 694 * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded 695 * return null. The position within the descriptor will not be changed when 696 * this returns, so the descriptor can be used again as-is. 697 * 698 * @param fd The file descriptor containing the bitmap data to decode 699 * @param outPadding If not null, return the padding rect for the bitmap if 700 * it exists, otherwise set padding to [-1,-1,-1,-1]. If 701 * no bitmap is returned (null) then padding is 702 * unchanged. 703 * @param opts null-ok; Options that control downsampling and whether the 704 * image should be completely decoded, or just its size returned. 705 * @return the decoded bitmap, or null 706 * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig} 707 * is {@link android.graphics.Bitmap.Config#HARDWARE} 708 * and {@link BitmapFactory.Options#inMutable} is set. 709 */ 710 public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) { 711 validate(opts); 712 Bitmap bm; 713 714 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeFileDescriptor"); 715 try { 716 if (nativeIsSeekable(fd)) { 717 bm = nativeDecodeFileDescriptor(fd, outPadding, opts); 718 } else { 719 FileInputStream fis = new FileInputStream(fd); 720 try { 721 bm = decodeStreamInternal(fis, outPadding, opts); 722 } finally { 723 try { 724 fis.close(); 725 } catch (Throwable t) {/* ignore */} 726 } 727 } 728 729 if (bm == null && opts != null && opts.inBitmap != null) { 730 throw new IllegalArgumentException("Problem decoding into existing bitmap"); 731 } 732 733 setDensityFromOptions(bm, opts); 734 } finally { 735 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS); 736 } 737 return bm; 738 } 739 740 /** 741 * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded 742 * return null. The position within the descriptor will not be changed when 743 * this returns, so the descriptor can be used again as is. 744 * 745 * @param fd The file descriptor containing the bitmap data to decode 746 * @return the decoded bitmap, or null 747 */ 748 public static Bitmap decodeFileDescriptor(FileDescriptor fd) { 749 return decodeFileDescriptor(fd, null, null); 750 } 751 752 private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage, 753 Rect padding, Options opts); 754 private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd, 755 Rect padding, Options opts); 756 private static native Bitmap nativeDecodeAsset(long nativeAsset, Rect padding, Options opts); 757 private static native Bitmap nativeDecodeByteArray(byte[] data, int offset, 758 int length, Options opts); 759 private static native boolean nativeIsSeekable(FileDescriptor fd); 760} 761