BitmapFactory.java revision 1b22b979256cf163ab9bbfd4fcfa16a8ce862ed1
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         * Normally bitmap allocations count against the dalvik heap, which
133         * means they help trigger GCs when a lot have been allocated. However,
134         * in rare cases, the caller may want to allocate the bitmap outside of
135         * that heap. To request that, set inNativeAlloc to true. In these
136         * rare instances, it is solely up to the caller to ensure that OOM is
137         * managed explicitly by calling bitmap.recycle() as soon as such a
138         * bitmap is no longer needed.
139         *
140         * @hide pending API council approval
141         */
142        public boolean inNativeAlloc;
143
144        /**
145         * The resulting width of the bitmap, set independent of the state of
146         * inJustDecodeBounds. However, if there is an error trying to decode,
147         * outWidth will be set to -1.
148         */
149        public int outWidth;
150
151        /**
152         * The resulting height of the bitmap, set independent of the state of
153         * inJustDecodeBounds. However, if there is an error trying to decode,
154         * outHeight will be set to -1.
155         */
156        public int outHeight;
157
158        /**
159         * If known, this string is set to the mimetype of the decoded image.
160         * If not know, or there is an error, it is set to null.
161         */
162        public String outMimeType;
163
164        /**
165         * Temp storage to use for decoding.  Suggest 16K or so.
166         */
167        public byte[] inTempStorage;
168
169        private native void requestCancel();
170
171        /**
172         * Flag to indicate that cancel has been called on this object.  This
173         * is useful if there's an intermediary that wants to first decode the
174         * bounds and then decode the image.  In that case the intermediary
175         * can check, inbetween the bounds decode and the image decode, to see
176         * if the operation is canceled.
177         */
178        public boolean mCancel;
179
180        /**
181         *  This can be called from another thread while this options object is
182         *  inside a decode... call. Calling this will notify the decoder that
183         *  it should cancel its operation. This is not guaranteed to cancel
184         *  the decode, but if it does, the decoder... operation will return
185         *  null, or if inJustDecodeBounds is true, will set outWidth/outHeight
186         *  to -1
187         */
188        public void requestCancelDecode() {
189            mCancel = true;
190            requestCancel();
191        }
192    }
193
194    /**
195     * Decode a file path into a bitmap. If the specified file name is null,
196     * or cannot be decoded into a bitmap, the function returns null.
197     *
198     * @param pathName complete path name for the file to be decoded.
199     * @param opts null-ok; Options that control downsampling and whether the
200     *             image should be completely decoded, or just is size returned.
201     * @return The decoded bitmap, or null if the image data could not be
202     *         decoded, or, if opts is non-null, if opts requested only the
203     *         size be returned (in opts.outWidth and opts.outHeight)
204     */
205    public static Bitmap decodeFile(String pathName, Options opts) {
206        Bitmap bm = null;
207        InputStream stream = null;
208        try {
209            stream = new FileInputStream(pathName);
210            bm = decodeStream(stream, null, opts);
211        } catch (Exception e) {
212            /*  do nothing.
213                If the exception happened on open, bm will be null.
214            */
215        } finally {
216            if (stream != null) {
217                try {
218                    stream.close();
219                } catch (IOException e) {
220                    // do nothing here
221                }
222            }
223        }
224        return bm;
225    }
226
227    /**
228     * Decode a file path into a bitmap. If the specified file name is null,
229     * or cannot be decoded into a bitmap, the function returns null.
230     *
231     * @param pathName complete path name for the file to be decoded.
232     * @return the resulting decoded bitmap, or null if it could not be decoded.
233     */
234    public static Bitmap decodeFile(String pathName) {
235        return decodeFile(pathName, null);
236    }
237
238    /**
239     * Decode a new Bitmap from an InputStream. This InputStream was obtained from
240     * resources, which we pass to be able to scale the bitmap accordingly.
241     *
242     * @hide
243     */
244    public static Bitmap decodeStream(Resources res, TypedValue value, InputStream is,
245            Rect pad, Options opts) {
246
247        if (opts == null) {
248            opts = new Options();
249        }
250
251        Bitmap bm = decodeStream(is, pad, opts);
252
253        if (bm != null && res != null && value != null) {
254            byte[] np = bm.getNinePatchChunk();
255            final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
256
257            final int density = value.density;
258            if (opts.inDensity == 0) {
259                opts.inDensity = density == TypedValue.DENSITY_DEFAULT ?
260                        DisplayMetrics.DEFAULT_DENSITY : density;
261            }
262            float scale = opts.inDensity / (float) DisplayMetrics.DEFAULT_DENSITY;
263
264            if (opts.inScaled || isNinePatch) {
265                bm.setDensityScale(1.0f);
266                bm.setAutoScalingEnabled(false);
267                // Assume we are going to prescale for the screen
268                scale = res.getDisplayMetrics().density / scale;
269                if (scale != 1.0f) {
270                    // TODO: This is very inefficient and should be done in native by Skia
271                    final Bitmap oldBitmap = bm;
272                    bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
273                            (int) (bm.getHeight() * scale + 0.5f), true);
274                    oldBitmap.recycle();
275
276                    if (isNinePatch) {
277                        np = nativeScaleNinePatch(np, scale, pad);
278                        bm.setNinePatchChunk(np);
279                    }
280                }
281            } else {
282                bm.setDensityScale(scale);
283                bm.setAutoScalingEnabled(true);
284            }
285        }
286
287        return bm;
288    }
289
290    /**
291     * Decode an image referenced by a resource ID.
292     *
293     * @param res   The resources object containing the image data
294     * @param id The resource id of the image data
295     * @param opts null-ok; Options that control downsampling and whether the
296     *             image should be completely decoded, or just is size returned.
297     * @return The decoded bitmap, or null if the image data could not be
298     *         decoded, or, if opts is non-null, if opts requested only the
299     *         size be returned (in opts.outWidth and opts.outHeight)
300     */
301    public static Bitmap decodeResource(Resources res, int id, Options opts) {
302        Bitmap bm = null;
303
304        try {
305            final TypedValue value = new TypedValue();
306            final InputStream is = res.openRawResource(id, value);
307
308            bm = decodeStream(res, value, is, null, opts);
309            is.close();
310        } catch (java.io.IOException e) {
311            /*  do nothing.
312                If the exception happened on open, bm will be null.
313                If it happened on close, bm is still valid.
314            */
315        }
316        return bm;
317    }
318
319    /**
320     * Decode an image referenced by a resource ID.
321     *
322     * @param res The resources object containing the image data
323     * @param id The resource id of the image data
324     * @return The decoded bitmap, or null if the image could not be decode.
325     */
326    public static Bitmap decodeResource(Resources res, int id) {
327        return decodeResource(res, id, null);
328    }
329
330    /**
331     * Decode an immutable bitmap from the specified byte array.
332     *
333     * @param data byte array of compressed image data
334     * @param offset offset into imageData for where the decoder should begin
335     *               parsing.
336     * @param length the number of bytes, beginning at offset, to parse
337     * @param opts null-ok; Options that control downsampling and whether the
338     *             image should be completely decoded, or just is size returned.
339     * @return The decoded bitmap, or null if the image data could not be
340     *         decoded, or, if opts is non-null, if opts requested only the
341     *         size be returned (in opts.outWidth and opts.outHeight)
342     */
343    public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
344        if ((offset | length) < 0 || data.length < offset + length) {
345            throw new ArrayIndexOutOfBoundsException();
346        }
347        return nativeDecodeByteArray(data, offset, length, opts);
348    }
349
350    /**
351     * Decode an immutable bitmap from the specified byte array.
352     *
353     * @param data byte array of compressed image data
354     * @param offset offset into imageData for where the decoder should begin
355     *               parsing.
356     * @param length the number of bytes, beginning at offset, to parse
357     * @return The decoded bitmap, or null if the image could not be decode.
358     */
359    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
360        return decodeByteArray(data, offset, length, null);
361    }
362
363    /**
364     * Decode an input stream into a bitmap. If the input stream is null, or
365     * cannot be used to decode a bitmap, the function returns null.
366     * The stream's position will be where ever it was after the encoded data
367     * was read.
368     *
369     * @param is The input stream that holds the raw data to be decoded into a
370     *           bitmap.
371     * @param outPadding If not null, return the padding rect for the bitmap if
372     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
373     *                   no bitmap is returned (null) then padding is
374     *                   unchanged.
375     * @param opts null-ok; Options that control downsampling and whether the
376     *             image should be completely decoded, or just is size returned.
377     * @return The decoded bitmap, or null if the image data could not be
378     *         decoded, or, if opts is non-null, if opts requested only the
379     *         size be returned (in opts.outWidth and opts.outHeight)
380     */
381    public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
382        // we don't throw in this case, thus allowing the caller to only check
383        // the cache, and not force the image to be decoded.
384        if (is == null) {
385            return null;
386        }
387
388        // we need mark/reset to work properly
389
390        if (!is.markSupported()) {
391            is = new BufferedInputStream(is, 16 * 1024);
392        }
393
394        // so we can call reset() if a given codec gives up after reading up to
395        // this many bytes. FIXME: need to find out from the codecs what this
396        // value should be.
397        is.mark(1024);
398
399        Bitmap  bm;
400
401        if (is instanceof AssetManager.AssetInputStream) {
402            bm = nativeDecodeAsset(((AssetManager.AssetInputStream) is).getAssetInt(),
403                    outPadding, opts);
404        } else {
405            // pass some temp storage down to the native code. 1024 is made up,
406            // but should be large enough to avoid too many small calls back
407            // into is.read(...) This number is not related to the value passed
408            // to mark(...) above.
409            byte [] tempStorage = null;
410            if (opts != null)
411                tempStorage = opts.inTempStorage;
412            if (tempStorage == null)
413                tempStorage = new byte[16 * 1024];
414            bm = nativeDecodeStream(is, tempStorage, outPadding, opts);
415        }
416
417        return bm;
418    }
419
420    /**
421     * Decode an input stream into a bitmap. If the input stream is null, or
422     * cannot be used to decode a bitmap, the function returns null.
423     * The stream's position will be where ever it was after the encoded data
424     * was read.
425     *
426     * @param is The input stream that holds the raw data to be decoded into a
427     *           bitmap.
428     * @return The decoded bitmap, or null if the image data could not be
429     *         decoded, or, if opts is non-null, if opts requested only the
430     *         size be returned (in opts.outWidth and opts.outHeight)
431     */
432    public static Bitmap decodeStream(InputStream is) {
433        return decodeStream(is, null, null);
434    }
435
436    /**
437     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
438     * return null. The position within the descriptor will not be changed when
439     * this returns, so the descriptor can be used again as is.
440     *
441     * @param fd The file descriptor containing the bitmap data to decode
442     * @param outPadding If not null, return the padding rect for the bitmap if
443     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
444     *                   no bitmap is returned (null) then padding is
445     *                   unchanged.
446     * @param opts null-ok; Options that control downsampling and whether the
447     *             image should be completely decoded, or just is size returned.
448     * @return the decoded bitmap, or null
449     */
450    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
451        return nativeDecodeFileDescriptor(fd, outPadding, opts);
452    }
453
454    /**
455     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
456     * return null. The position within the descriptor will not be changed when
457     * this returns, so the descriptor can be used again as is.
458     *
459     * @param fd The file descriptor containing the bitmap data to decode
460     * @return the decoded bitmap, or null
461     */
462    public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
463        return nativeDecodeFileDescriptor(fd, null, null);
464    }
465
466    private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
467            Rect padding, Options opts);
468    private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
469            Rect padding, Options opts);
470    private static native Bitmap nativeDecodeAsset(int asset, Rect padding, Options opts);
471    private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
472            int length, Options opts);
473    private static native byte[] nativeScaleNinePatch(byte[] chunk, float scale, Rect pad);
474}
475
476