BitmapFactory.java revision cf4550c3198d6b3d92cdc52707fe70d7cc0caa9f
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.util.DisplayMetrics;
22import android.util.TypedValue;
23
24import java.io.BufferedInputStream;
25import java.io.FileDescriptor;
26import java.io.FileInputStream;
27import java.io.IOException;
28import java.io.InputStream;
29
30/**
31 * Creates Bitmap objects from various sources, including files, streams,
32 * and byte-arrays.
33 */
34public class BitmapFactory {
35    public static class Options {
36        /**
37         * Create a default Options object, which if left unchanged will give
38         * the same result from the decoder as if null were passed.
39         */
40        public Options() {
41            inDither = true;
42            inDensity = 0;
43            inScaled = true;
44        }
45
46        /**
47         * If set to true, the decoder will return null (no bitmap), but
48         * the out... fields will still be set, allowing the caller to query
49         * the bitmap without having to allocate the memory for its pixels.
50         */
51        public boolean inJustDecodeBounds;
52
53        /**
54         * If set to a value > 1, requests the decoder to subsample the original
55         * image, returning a smaller image to save memory. The sample size is
56         * the number of pixels in either dimension that correspond to a single
57         * pixel in the decoded bitmap. For example, inSampleSize == 4 returns
58         * an image that is 1/4 the width/height of the original, and 1/16 the
59         * number of pixels. Any value <= 1 is treated the same as 1. Note: the
60         * decoder will try to fulfill this request, but the resulting bitmap
61         * may have different dimensions that precisely what has been requested.
62         * Also, powers of 2 are often faster/easier for the decoder to honor.
63         */
64        public int inSampleSize;
65
66        /**
67         * If this is non-null, the decoder will try to decode into this
68         * internal configuration. If it is null, or the request cannot be met,
69         * the decoder will try to pick the best matching config based on the
70         * system's screen depth, and characteristics of the original image such
71         * as if it has per-pixel alpha (requiring a config that also does).
72         */
73        public Bitmap.Config inPreferredConfig;
74
75        /**
76         * If dither is true, the decoder will atttempt to dither the decoded
77         * image.
78         */
79        public boolean inDither;
80
81        /**
82         * The desired pixel density of the bitmap.
83         *
84         * @see android.util.DisplayMetrics#DEFAULT_DENSITY
85         * @see android.util.DisplayMetrics#density
86         *
87         * @hide pending API council approval
88         */
89        public int inDensity;
90
91        /**
92         * </p>If the bitmap is loaded from {@link android.content.res.Resources} and
93         * this flag is turned on, the bitmap will be scaled to match the default
94         * display's pixel density.</p>
95         *
96         * </p>This flag is turned on by default and should be turned off if you need
97         * a non-scaled version of the bitmap. In this case,
98         * {@link android.graphics.Bitmap#setAutoScalingEnabled(boolean)} can be used
99         * to properly scale the bitmap at drawing time.</p>
100         *
101         * @hide pending API council approval
102         */
103        public boolean inScaled;
104
105        /**
106         * If this is set to true, then the resulting bitmap will allocate its
107         * pixels such that they can be purged if the system needs to reclaim
108         * memory. In that instance, when the pixels need to be accessed again
109         * (e.g. the bitmap is drawn, getPixels() is called), they will be
110         * automatically re-decoded.
111         *
112         * For the re-decode to happen, the bitmap must have access to the
113         * encoded data, either by sharing a reference to the input
114         * or by making a copy of it. This distinction is controlled by
115         * inInputShareable. If this is true, then the bitmap may keep a shallow
116         * reference to the input. If this is false, then the bitmap will
117         * explicitly make a copy of the input data, and keep that. Even if
118         * sharing is allowed, the implementation may still decide to make a
119         * deep copy of the input data.
120         */
121        public boolean inPurgeable;
122
123        /**
124         * This field works in conjuction with inPurgeable. If inPurgeable is
125         * false, then this field is ignored. If inPurgeable is true, then this
126         * field determines whether the bitmap can share a reference to the
127         * input data (inputstream, array, etc.) or if it must make a deep copy.
128         */
129        public boolean inInputShareable;
130
131        /**
132         * The resulting width of the bitmap, set independent of the state of
133         * inJustDecodeBounds. However, if there is an error trying to decode,
134         * outWidth will be set to -1.
135         */
136        public int outWidth;
137
138        /**
139         * The resulting height of the bitmap, set independent of the state of
140         * inJustDecodeBounds. However, if there is an error trying to decode,
141         * outHeight will be set to -1.
142         */
143        public int outHeight;
144
145        /**
146         * If known, this string is set to the mimetype of the decoded image.
147         * If not know, or there is an error, it is set to null.
148         */
149        public String outMimeType;
150
151        /**
152         * Temp storage to use for decoding.  Suggest 16K or so.
153         */
154        public byte[] inTempStorage;
155
156        private native void requestCancel();
157
158        /**
159         * Flag to indicate that cancel has been called on this object.  This
160         * is useful if there's an intermediary that wants to first decode the
161         * bounds and then decode the image.  In that case the intermediary
162         * can check, inbetween the bounds decode and the image decode, to see
163         * if the operation is canceled.
164         */
165        public boolean mCancel;
166
167        /**
168         *  This can be called from another thread while this options object is
169         *  inside a decode... call. Calling this will notify the decoder that
170         *  it should cancel its operation. This is not guaranteed to cancel
171         *  the decode, but if it does, the decoder... operation will return
172         *  null, or if inJustDecodeBounds is true, will set outWidth/outHeight
173         *  to -1
174         */
175        public void requestCancelDecode() {
176            mCancel = true;
177            requestCancel();
178        }
179    }
180
181    /**
182     * Decode a file path into a bitmap. If the specified file name is null,
183     * or cannot be decoded into a bitmap, the function returns null.
184     *
185     * @param pathName complete path name for the file to be decoded.
186     * @param opts null-ok; Options that control downsampling and whether the
187     *             image should be completely decoded, or just is size returned.
188     * @return The decoded bitmap, or null if the image data could not be
189     *         decoded, or, if opts is non-null, if opts requested only the
190     *         size be returned (in opts.outWidth and opts.outHeight)
191     */
192    public static Bitmap decodeFile(String pathName, Options opts) {
193        Bitmap bm = null;
194        InputStream stream = null;
195        try {
196            stream = new FileInputStream(pathName);
197            bm = decodeStream(stream, null, opts);
198        } catch (Exception e) {
199            /*  do nothing.
200                If the exception happened on open, bm will be null.
201            */
202        } finally {
203            if (stream != null) {
204                try {
205                    stream.close();
206                } catch (IOException e) {
207                    // do nothing here
208                }
209            }
210        }
211        return bm;
212    }
213
214    /**
215     * Decode a file path into a bitmap. If the specified file name is null,
216     * or cannot be decoded into a bitmap, the function returns null.
217     *
218     * @param pathName complete path name for the file to be decoded.
219     * @return the resulting decoded bitmap, or null if it could not be decoded.
220     */
221    public static Bitmap decodeFile(String pathName) {
222        return decodeFile(pathName, null);
223    }
224
225    /**
226     * Decode a new Bitmap from an InputStream. This InputStream was obtained from
227     * resources, which we pass to be able to scale the bitmap accordingly.
228     *
229     * @hide
230     */
231    public static Bitmap decodeStream(Resources res, TypedValue value, InputStream is,
232            Rect pad, Options opts) {
233
234        if (opts == null) {
235            opts = new Options();
236        }
237
238        Bitmap bm = decodeStream(is, pad, opts);
239
240        if (bm != null && res != null && value != null) {
241            byte[] np = bm.getNinePatchChunk();
242            final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
243
244            final int density = value.density;
245            if (opts.inDensity == 0) {
246                opts.inDensity = density == TypedValue.DENSITY_DEFAULT ?
247                        DisplayMetrics.DEFAULT_DENSITY : density;
248            }
249            float scale = opts.inDensity / (float) DisplayMetrics.DEFAULT_DENSITY;
250
251            if (opts.inScaled || isNinePatch) {
252                bm.setDensityScale(1.0f);
253                bm.setAutoScalingEnabled(false);
254                // Assume we are going to prescale for the screen
255                scale = res.getDisplayMetrics().density / scale;
256                if (scale != 1.0f) {
257                    // TODO: This is very inefficient and should be done in native by Skia
258                    final Bitmap oldBitmap = bm;
259                    bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
260                            (int) (bm.getHeight() * scale + 0.5f), true);
261                    oldBitmap.recycle();
262
263                    if (isNinePatch) {
264                        np = nativeScaleNinePatch(np, scale, pad);
265                        bm.setNinePatchChunk(np);
266                    }
267                }
268            } else {
269                bm.setDensityScale(scale);
270                bm.setAutoScalingEnabled(true);
271            }
272        }
273
274        return bm;
275    }
276
277    /**
278     * Decode an image referenced by a resource ID.
279     *
280     * @param res   The resources object containing the image data
281     * @param id The resource id of the image data
282     * @param opts null-ok; Options that control downsampling and whether the
283     *             image should be completely decoded, or just is size returned.
284     * @return The decoded bitmap, or null if the image data could not be
285     *         decoded, or, if opts is non-null, if opts requested only the
286     *         size be returned (in opts.outWidth and opts.outHeight)
287     */
288    public static Bitmap decodeResource(Resources res, int id, Options opts) {
289        Bitmap bm = null;
290
291        try {
292            final TypedValue value = new TypedValue();
293            final InputStream is = res.openRawResource(id, value);
294
295            bm = decodeStream(res, value, is, null, opts);
296            is.close();
297        } catch (java.io.IOException e) {
298            /*  do nothing.
299                If the exception happened on open, bm will be null.
300                If it happened on close, bm is still valid.
301            */
302        }
303        return bm;
304    }
305
306    /**
307     * Decode an image referenced by a resource ID.
308     *
309     * @param res The resources object containing the image data
310     * @param id The resource id of the image data
311     * @return The decoded bitmap, or null if the image could not be decode.
312     */
313    public static Bitmap decodeResource(Resources res, int id) {
314        return decodeResource(res, id, null);
315    }
316
317    /**
318     * Decode an immutable bitmap from the specified byte array.
319     *
320     * @param data byte array of compressed image data
321     * @param offset offset into imageData for where the decoder should begin
322     *               parsing.
323     * @param length the number of bytes, beginning at offset, to parse
324     * @param opts null-ok; Options that control downsampling and whether the
325     *             image should be completely decoded, or just is size returned.
326     * @return The decoded bitmap, or null if the image data could not be
327     *         decoded, or, if opts is non-null, if opts requested only the
328     *         size be returned (in opts.outWidth and opts.outHeight)
329     */
330    public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
331        if ((offset | length) < 0 || data.length < offset + length) {
332            throw new ArrayIndexOutOfBoundsException();
333        }
334        return nativeDecodeByteArray(data, offset, length, opts);
335    }
336
337    /**
338     * Decode an immutable bitmap from the specified byte array.
339     *
340     * @param data byte array of compressed image data
341     * @param offset offset into imageData for where the decoder should begin
342     *               parsing.
343     * @param length the number of bytes, beginning at offset, to parse
344     * @return The decoded bitmap, or null if the image could not be decode.
345     */
346    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
347        return decodeByteArray(data, offset, length, null);
348    }
349
350    /**
351     * Decode an input stream into a bitmap. If the input stream is null, or
352     * cannot be used to decode a bitmap, the function returns null.
353     * The stream's position will be where ever it was after the encoded data
354     * was read.
355     *
356     * @param is The input stream that holds the raw data to be decoded into a
357     *           bitmap.
358     * @param outPadding If not null, return the padding rect for the bitmap if
359     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
360     *                   no bitmap is returned (null) then padding is
361     *                   unchanged.
362     * @param opts null-ok; Options that control downsampling and whether the
363     *             image should be completely decoded, or just is size returned.
364     * @return The decoded bitmap, or null if the image data could not be
365     *         decoded, or, if opts is non-null, if opts requested only the
366     *         size be returned (in opts.outWidth and opts.outHeight)
367     */
368    public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
369        // we don't throw in this case, thus allowing the caller to only check
370        // the cache, and not force the image to be decoded.
371        if (is == null) {
372            return null;
373        }
374
375        // we need mark/reset to work properly
376
377        if (!is.markSupported()) {
378            is = new BufferedInputStream(is, 16 * 1024);
379        }
380
381        // so we can call reset() if a given codec gives up after reading up to
382        // this many bytes. FIXME: need to find out from the codecs what this
383        // value should be.
384        is.mark(1024);
385
386        Bitmap  bm;
387
388        if (is instanceof AssetManager.AssetInputStream) {
389            bm = nativeDecodeAsset(((AssetManager.AssetInputStream) is).getAssetInt(),
390                    outPadding, opts);
391        } else {
392            // pass some temp storage down to the native code. 1024 is made up,
393            // but should be large enough to avoid too many small calls back
394            // into is.read(...) This number is not related to the value passed
395            // to mark(...) above.
396            byte [] tempStorage = null;
397            if (opts != null)
398                tempStorage = opts.inTempStorage;
399            if (tempStorage == null)
400                tempStorage = new byte[16 * 1024];
401            bm = nativeDecodeStream(is, tempStorage, outPadding, opts);
402        }
403
404        return bm;
405    }
406
407    /**
408     * Decode an input stream into a bitmap. If the input stream is null, or
409     * cannot be used to decode a bitmap, the function returns null.
410     * The stream's position will be where ever it was after the encoded data
411     * was read.
412     *
413     * @param is The input stream that holds the raw data to be decoded into a
414     *           bitmap.
415     * @return The decoded bitmap, or null if the image data could not be
416     *         decoded, or, if opts is non-null, if opts requested only the
417     *         size be returned (in opts.outWidth and opts.outHeight)
418     */
419    public static Bitmap decodeStream(InputStream is) {
420        return decodeStream(is, null, null);
421    }
422
423    /**
424     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
425     * return null. The position within the descriptor will not be changed when
426     * this returns, so the descriptor can be used again as is.
427     *
428     * @param fd The file descriptor containing the bitmap data to decode
429     * @param outPadding If not null, return the padding rect for the bitmap if
430     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
431     *                   no bitmap is returned (null) then padding is
432     *                   unchanged.
433     * @param opts null-ok; Options that control downsampling and whether the
434     *             image should be completely decoded, or just is size returned.
435     * @return the decoded bitmap, or null
436     */
437    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
438        return nativeDecodeFileDescriptor(fd, outPadding, opts);
439    }
440
441    /**
442     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
443     * return null. The position within the descriptor will not be changed when
444     * this returns, so the descriptor can be used again as is.
445     *
446     * @param fd The file descriptor containing the bitmap data to decode
447     * @return the decoded bitmap, or null
448     */
449    public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
450        return nativeDecodeFileDescriptor(fd, null, null);
451    }
452
453    private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
454            Rect padding, Options opts);
455    private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
456            Rect padding, Options opts);
457    private static native Bitmap nativeDecodeAsset(int asset, Rect padding, Options opts);
458    private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
459            int length, Options opts);
460    private static native byte[] nativeScaleNinePatch(byte[] chunk, float scale, Rect pad);
461}
462
463