BitmapFactory.java revision 5b15b1717ef95ef8c91f8587fee1f789aec6ae49
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 android.content.res.AssetManager;
20import android.content.res.Resources;
21import android.os.Trace;
22import android.util.DisplayMetrics;
23import android.util.Log;
24import android.util.TypedValue;
25
26import java.io.FileDescriptor;
27import java.io.FileInputStream;
28import java.io.IOException;
29import java.io.InputStream;
30
31/**
32 * Creates Bitmap objects from various sources, including files, streams,
33 * and byte-arrays.
34 */
35public 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         */
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         * @see Bitmap#hasAlpha()
157         * @see Bitmap#isPremultiplied()
158         */
159        public boolean inPremultiplied;
160
161        /**
162         * If dither is true, the decoder will attempt to dither the decoded
163         * image.
164         */
165        public boolean inDither;
166
167        /**
168         * The pixel density to use for the bitmap.  This will always result
169         * in the returned bitmap having a density set for it (see
170         * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}).  In addition,
171         * if {@link #inScaled} is set (which it is by default} and this
172         * density does not match {@link #inTargetDensity}, then the bitmap
173         * will be scaled to the target density before being returned.
174         *
175         * <p>If this is 0,
176         * {@link BitmapFactory#decodeResource(Resources, int)},
177         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
178         * and {@link BitmapFactory#decodeResourceStream}
179         * will fill in the density associated with the resource.  The other
180         * functions will leave it as-is and no density will be applied.
181         *
182         * @see #inTargetDensity
183         * @see #inScreenDensity
184         * @see #inScaled
185         * @see Bitmap#setDensity(int)
186         * @see android.util.DisplayMetrics#densityDpi
187         */
188        public int inDensity;
189
190        /**
191         * The pixel density of the destination this bitmap will be drawn to.
192         * This is used in conjunction with {@link #inDensity} and
193         * {@link #inScaled} to determine if and how to scale the bitmap before
194         * returning it.
195         *
196         * <p>If this is 0,
197         * {@link BitmapFactory#decodeResource(Resources, int)},
198         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
199         * and {@link BitmapFactory#decodeResourceStream}
200         * will fill in the density associated the Resources object's
201         * DisplayMetrics.  The other
202         * functions will leave it as-is and no scaling for density will be
203         * performed.
204         *
205         * @see #inDensity
206         * @see #inScreenDensity
207         * @see #inScaled
208         * @see android.util.DisplayMetrics#densityDpi
209         */
210        public int inTargetDensity;
211
212        /**
213         * The pixel density of the actual screen that is being used.  This is
214         * purely for applications running in density compatibility code, where
215         * {@link #inTargetDensity} is actually the density the application
216         * sees rather than the real screen density.
217         *
218         * <p>By setting this, you
219         * allow the loading code to avoid scaling a bitmap that is currently
220         * in the screen density up/down to the compatibility density.  Instead,
221         * if {@link #inDensity} is the same as {@link #inScreenDensity}, the
222         * bitmap will be left as-is.  Anything using the resulting bitmap
223         * must also used {@link Bitmap#getScaledWidth(int)
224         * Bitmap.getScaledWidth} and {@link Bitmap#getScaledHeight
225         * Bitmap.getScaledHeight} to account for any different between the
226         * bitmap's density and the target's density.
227         *
228         * <p>This is never set automatically for the caller by
229         * {@link BitmapFactory} itself.  It must be explicitly set, since the
230         * caller must deal with the resulting bitmap in a density-aware way.
231         *
232         * @see #inDensity
233         * @see #inTargetDensity
234         * @see #inScaled
235         * @see android.util.DisplayMetrics#densityDpi
236         */
237        public int inScreenDensity;
238
239        /**
240         * When this flag is set, if {@link #inDensity} and
241         * {@link #inTargetDensity} are not 0, the
242         * bitmap will be scaled to match {@link #inTargetDensity} when loaded,
243         * rather than relying on the graphics system scaling it each time it
244         * is drawn to a Canvas.
245         *
246         * <p>BitmapRegionDecoder ignores this flag, and will not scale output
247         * based on density. (though {@link #inSampleSize} is supported)</p>
248         *
249         * <p>This flag is turned on by default and should be turned off if you need
250         * a non-scaled version of the bitmap.  Nine-patch bitmaps ignore this
251         * flag and are always scaled.
252         */
253        public boolean inScaled;
254
255        /**
256         * If this is set to true, then the resulting bitmap will allocate its
257         * pixels such that they can be purged if the system needs to reclaim
258         * memory. In that instance, when the pixels need to be accessed again
259         * (e.g. the bitmap is drawn, getPixels() is called), they will be
260         * automatically re-decoded.
261         *
262         * <p>For the re-decode to happen, the bitmap must have access to the
263         * encoded data, either by sharing a reference to the input
264         * or by making a copy of it. This distinction is controlled by
265         * inInputShareable. If this is true, then the bitmap may keep a shallow
266         * reference to the input. If this is false, then the bitmap will
267         * explicitly make a copy of the input data, and keep that. Even if
268         * sharing is allowed, the implementation may still decide to make a
269         * deep copy of the input data.</p>
270         *
271         * <p>While inPurgeable can help avoid big Dalvik heap allocations (from
272         * API level 11 onward), it sacrifices performance predictability since any
273         * image that the view system tries to draw may incur a decode delay which
274         * can lead to dropped frames. Therefore, most apps should avoid using
275         * inPurgeable to allow for a fast and fluid UI. To minimize Dalvik heap
276         * allocations use the {@link #inBitmap} flag instead.</p>
277         *
278         * <p class="note"><strong>Note:</strong> This flag is ignored when used
279         * with {@link #decodeResource(Resources, int,
280         * android.graphics.BitmapFactory.Options)} or {@link #decodeFile(String,
281         * android.graphics.BitmapFactory.Options)}.</p>
282         */
283        public boolean inPurgeable;
284
285        /**
286         * This field works in conjuction with inPurgeable. If inPurgeable is
287         * false, then this field is ignored. If inPurgeable is true, then this
288         * field determines whether the bitmap can share a reference to the
289         * input data (inputstream, array, etc.) or if it must make a deep copy.
290         */
291        public boolean inInputShareable;
292
293        /**
294         * If inPreferQualityOverSpeed is set to true, the decoder will try to
295         * decode the reconstructed image to a higher quality even at the
296         * expense of the decoding speed. Currently the field only affects JPEG
297         * decode, in the case of which a more accurate, but slightly slower,
298         * IDCT method will be used instead.
299         */
300        public boolean inPreferQualityOverSpeed;
301
302        /**
303         * The resulting width of the bitmap, set independent of the state of
304         * inJustDecodeBounds. However, if there is an error trying to decode,
305         * outWidth will be set to -1.
306         */
307
308        public int outWidth;
309
310        /**
311         * The resulting height of the bitmap, set independent of the state of
312         * inJustDecodeBounds. However, if there is an error trying to decode,
313         * outHeight will be set to -1.
314         */
315        public int outHeight;
316
317        /**
318         * If known, this string is set to the mimetype of the decoded image.
319         * If not know, or there is an error, it is set to null.
320         */
321        public String outMimeType;
322
323        /**
324         * Temp storage to use for decoding.  Suggest 16K or so.
325         */
326        public byte[] inTempStorage;
327
328        private native void requestCancel();
329
330        /**
331         * Flag to indicate that cancel has been called on this object.  This
332         * is useful if there's an intermediary that wants to first decode the
333         * bounds and then decode the image.  In that case the intermediary
334         * can check, inbetween the bounds decode and the image decode, to see
335         * if the operation is canceled.
336         */
337        public boolean mCancel;
338
339        /**
340         *  This can be called from another thread while this options object is
341         *  inside a decode... call. Calling this will notify the decoder that
342         *  it should cancel its operation. This is not guaranteed to cancel
343         *  the decode, but if it does, the decoder... operation will return
344         *  null, or if inJustDecodeBounds is true, will set outWidth/outHeight
345         *  to -1
346         */
347        public void requestCancelDecode() {
348            mCancel = true;
349            requestCancel();
350        }
351    }
352
353    /**
354     * Decode a file path into a bitmap. If the specified file name is null,
355     * or cannot be decoded into a bitmap, the function returns null.
356     *
357     * @param pathName complete path name for the file to be decoded.
358     * @param opts null-ok; Options that control downsampling and whether the
359     *             image should be completely decoded, or just is size returned.
360     * @return The decoded bitmap, or null if the image data could not be
361     *         decoded, or, if opts is non-null, if opts requested only the
362     *         size be returned (in opts.outWidth and opts.outHeight)
363     */
364    public static Bitmap decodeFile(String pathName, Options opts) {
365        Bitmap bm = null;
366        InputStream stream = null;
367        try {
368            stream = new FileInputStream(pathName);
369            bm = decodeStream(stream, null, opts);
370        } catch (Exception e) {
371            /*  do nothing.
372                If the exception happened on open, bm will be null.
373            */
374            Log.e("BitmapFactory", "Unable to decode stream: " + e);
375        } finally {
376            if (stream != null) {
377                try {
378                    stream.close();
379                } catch (IOException e) {
380                    // do nothing here
381                }
382            }
383        }
384        return bm;
385    }
386
387    /**
388     * Decode a file path into a bitmap. If the specified file name is null,
389     * or cannot be decoded into a bitmap, the function returns null.
390     *
391     * @param pathName complete path name for the file to be decoded.
392     * @return the resulting decoded bitmap, or null if it could not be decoded.
393     */
394    public static Bitmap decodeFile(String pathName) {
395        return decodeFile(pathName, null);
396    }
397
398    /**
399     * Decode a new Bitmap from an InputStream. This InputStream was obtained from
400     * resources, which we pass to be able to scale the bitmap accordingly.
401     */
402    public static Bitmap decodeResourceStream(Resources res, TypedValue value,
403            InputStream is, Rect pad, Options opts) {
404
405        if (opts == null) {
406            opts = new Options();
407        }
408
409        if (opts.inDensity == 0 && value != null) {
410            final int density = value.density;
411            if (density == TypedValue.DENSITY_DEFAULT) {
412                opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
413            } else if (density != TypedValue.DENSITY_NONE) {
414                opts.inDensity = density;
415            }
416        }
417
418        if (opts.inTargetDensity == 0 && res != null) {
419            opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
420        }
421
422        return decodeStream(is, pad, opts);
423    }
424
425    /**
426     * Synonym for opening the given resource and calling
427     * {@link #decodeResourceStream}.
428     *
429     * @param res   The resources object containing the image data
430     * @param id The resource id of the image data
431     * @param opts null-ok; Options that control downsampling and whether the
432     *             image should be completely decoded, or just is size returned.
433     * @return The decoded bitmap, or null if the image data could not be
434     *         decoded, or, if opts is non-null, if opts requested only the
435     *         size be returned (in opts.outWidth and opts.outHeight)
436     */
437    public static Bitmap decodeResource(Resources res, int id, Options opts) {
438        Bitmap bm = null;
439        InputStream is = null;
440
441        try {
442            final TypedValue value = new TypedValue();
443            is = res.openRawResource(id, value);
444
445            bm = decodeResourceStream(res, value, is, null, opts);
446        } catch (Exception e) {
447            /*  do nothing.
448                If the exception happened on open, bm will be null.
449                If it happened on close, bm is still valid.
450            */
451        } finally {
452            try {
453                if (is != null) is.close();
454            } catch (IOException e) {
455                // Ignore
456            }
457        }
458
459        if (bm == null && opts != null && opts.inBitmap != null) {
460            throw new IllegalArgumentException("Problem decoding into existing bitmap");
461        }
462
463        return bm;
464    }
465
466    /**
467     * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}
468     * with null Options.
469     *
470     * @param res The resources object containing the image data
471     * @param id The resource id of the image data
472     * @return The decoded bitmap, or null if the image could not be decoded.
473     */
474    public static Bitmap decodeResource(Resources res, int id) {
475        return decodeResource(res, id, null);
476    }
477
478    /**
479     * Decode an immutable bitmap from the specified byte array.
480     *
481     * @param data byte array of compressed image data
482     * @param offset offset into imageData for where the decoder should begin
483     *               parsing.
484     * @param length the number of bytes, beginning at offset, to parse
485     * @param opts null-ok; Options that control downsampling and whether the
486     *             image should be completely decoded, or just is size returned.
487     * @return The decoded bitmap, or null if the image data could not be
488     *         decoded, or, if opts is non-null, if opts requested only the
489     *         size be returned (in opts.outWidth and opts.outHeight)
490     */
491    public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
492        if ((offset | length) < 0 || data.length < offset + length) {
493            throw new ArrayIndexOutOfBoundsException();
494        }
495
496        Bitmap bm;
497
498        Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap");
499        try {
500            bm = nativeDecodeByteArray(data, offset, length, opts);
501
502            if (bm == null && opts != null && opts.inBitmap != null) {
503                throw new IllegalArgumentException("Problem decoding into existing bitmap");
504            }
505            setDensityFromOptions(bm, opts);
506        } finally {
507            Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
508        }
509
510        return bm;
511    }
512
513    /**
514     * Decode an immutable bitmap from the specified byte array.
515     *
516     * @param data byte array of compressed image data
517     * @param offset offset into imageData for where the decoder should begin
518     *               parsing.
519     * @param length the number of bytes, beginning at offset, to parse
520     * @return The decoded bitmap, or null if the image could not be decoded.
521     */
522    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
523        return decodeByteArray(data, offset, length, null);
524    }
525
526    /**
527     * Set the newly decoded bitmap's density based on the Options.
528     */
529    private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) {
530        if (outputBitmap == null || opts == null) return;
531
532        final int density = opts.inDensity;
533        if (density != 0) {
534            outputBitmap.setDensity(density);
535            final int targetDensity = opts.inTargetDensity;
536            if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
537                return;
538            }
539
540            byte[] np = outputBitmap.getNinePatchChunk();
541            final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
542            if (opts.inScaled || isNinePatch) {
543                outputBitmap.setDensity(targetDensity);
544            }
545        } else if (opts.inBitmap != null) {
546            // bitmap was reused, ensure density is reset
547            outputBitmap.setDensity(Bitmap.getDefaultDensity());
548        }
549    }
550
551    /**
552     * Decode an input stream into a bitmap. If the input stream is null, or
553     * cannot be used to decode a bitmap, the function returns null.
554     * The stream's position will be where ever it was after the encoded data
555     * was read.
556     *
557     * @param is The input stream that holds the raw data to be decoded into a
558     *           bitmap.
559     * @param outPadding If not null, return the padding rect for the bitmap if
560     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
561     *                   no bitmap is returned (null) then padding is
562     *                   unchanged.
563     * @param opts null-ok; Options that control downsampling and whether the
564     *             image should be completely decoded, or just is size returned.
565     * @return The decoded bitmap, or null if the image data could not be
566     *         decoded, or, if opts is non-null, if opts requested only the
567     *         size be returned (in opts.outWidth and opts.outHeight)
568     *
569     * <p class="note">Prior to {@link android.os.Build.VERSION_CODES#KITKAT},
570     * if {@link InputStream#markSupported is.markSupported()} returns true,
571     * <code>is.mark(1024)</code> would be called. As of
572     * {@link android.os.Build.VERSION_CODES#KITKAT}, this is no longer the case.</p>
573     */
574    public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
575        // we don't throw in this case, thus allowing the caller to only check
576        // the cache, and not force the image to be decoded.
577        if (is == null) {
578            return null;
579        }
580
581        Bitmap bm = null;
582
583        Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap");
584        try {
585            if (is instanceof AssetManager.AssetInputStream) {
586                final long asset = ((AssetManager.AssetInputStream) is).getNativeAsset();
587                bm = nativeDecodeAsset(asset, outPadding, opts);
588            } else {
589                bm = decodeStreamInternal(is, outPadding, opts);
590            }
591
592            if (bm == null && opts != null && opts.inBitmap != null) {
593                throw new IllegalArgumentException("Problem decoding into existing bitmap");
594            }
595
596            setDensityFromOptions(bm, opts);
597        } finally {
598            Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
599        }
600
601        return bm;
602    }
603
604    /**
605     * Private helper function for decoding an InputStream natively. Buffers the input enough to
606     * do a rewind as needed, and supplies temporary storage if necessary. is MUST NOT be null.
607     */
608    private static Bitmap decodeStreamInternal(InputStream is, Rect outPadding, Options opts) {
609        // ASSERT(is != null);
610        byte [] tempStorage = null;
611        if (opts != null) tempStorage = opts.inTempStorage;
612        if (tempStorage == null) tempStorage = new byte[DECODE_BUFFER_SIZE];
613        return nativeDecodeStream(is, tempStorage, outPadding, opts);
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     * @return The decoded bitmap, or null if the image data could not be decoded.
625     */
626    public static Bitmap decodeStream(InputStream is) {
627        return decodeStream(is, null, null);
628    }
629
630    /**
631     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
632     * return null. The position within the descriptor will not be changed when
633     * this returns, so the descriptor can be used again as-is.
634     *
635     * @param fd The file descriptor containing the bitmap data to decode
636     * @param outPadding If not null, return the padding rect for the bitmap if
637     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
638     *                   no bitmap is returned (null) then padding is
639     *                   unchanged.
640     * @param opts null-ok; Options that control downsampling and whether the
641     *             image should be completely decoded, or just its size returned.
642     * @return the decoded bitmap, or null
643     */
644    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
645        Bitmap bm;
646
647        Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeFileDescriptor");
648        try {
649            if (nativeIsSeekable(fd)) {
650                bm = nativeDecodeFileDescriptor(fd, outPadding, opts);
651            } else {
652                FileInputStream fis = new FileInputStream(fd);
653                try {
654                    bm = decodeStreamInternal(fis, outPadding, opts);
655                } finally {
656                    try {
657                        fis.close();
658                    } catch (Throwable t) {/* ignore */}
659                }
660            }
661
662            if (bm == null && opts != null && opts.inBitmap != null) {
663                throw new IllegalArgumentException("Problem decoding into existing bitmap");
664            }
665
666            setDensityFromOptions(bm, opts);
667        } finally {
668            Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
669        }
670        return bm;
671    }
672
673    /**
674     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
675     * return null. The position within the descriptor will not be changed when
676     * this returns, so the descriptor can be used again as is.
677     *
678     * @param fd The file descriptor containing the bitmap data to decode
679     * @return the decoded bitmap, or null
680     */
681    public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
682        return decodeFileDescriptor(fd, null, null);
683    }
684
685    private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
686            Rect padding, Options opts);
687    private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
688            Rect padding, Options opts);
689    private static native Bitmap nativeDecodeAsset(long nativeAsset, Rect padding, Options opts);
690    private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
691            int length, Options opts);
692    private static native boolean nativeIsSeekable(FileDescriptor fd);
693}
694