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