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