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 = false;
42            inScaled = true;
43        }
44
45        /**
46         * If set, decode methods that take the Options object will attempt to
47         * reuse this bitmap when loading content. If the decode operation cannot
48         * use this bitmap, the decode method will return <code>null</code> and
49         * will throw an IllegalArgumentException. The
50         * current implementation necessitates that the reused bitmap be of the
51         * same size as the source content and in jpeg or png format (whether as a
52         * resource or as a stream). The {@link android.graphics.Bitmap.Config
53         * configuration} of the reused bitmap will override the setting of
54         * {@link #inPreferredConfig}, if set.
55         *
56         * <p>You should still always use the returned Bitmap of the decode
57         * method and not assume that reusing the bitmap worked, due to the
58         * constraints outlined above and failure situations that can occur.
59         * Checking whether the return value matches the value of the inBitmap
60         * set in the Options structure is a way to see if the bitmap was reused,
61         * but in all cases you should use the returned Bitmap to make sure
62         * that you are using the bitmap that was used as the decode destination.</p>
63         */
64        public Bitmap inBitmap;
65
66        /**
67         * If set, decode methods will always return a mutable Bitmap instead of
68         * an immutable one. This can be used for instance to programmatically apply
69         * effects to a Bitmap loaded through BitmapFactory.
70         */
71        @SuppressWarnings({"UnusedDeclaration"}) // used in native code
72        public boolean inMutable;
73
74        /**
75         * If set to true, the decoder will return null (no bitmap), but
76         * the out... fields will still be set, allowing the caller to query
77         * the bitmap without having to allocate the memory for its pixels.
78         */
79        public boolean inJustDecodeBounds;
80
81        /**
82         * If set to a value > 1, requests the decoder to subsample the original
83         * image, returning a smaller image to save memory. The sample size is
84         * the number of pixels in either dimension that correspond to a single
85         * pixel in the decoded bitmap. For example, inSampleSize == 4 returns
86         * an image that is 1/4 the width/height of the original, and 1/16 the
87         * number of pixels. Any value <= 1 is treated the same as 1. Note: the
88         * decoder will try to fulfill this request, but the resulting bitmap
89         * may have different dimensions that precisely what has been requested.
90         * Also, powers of 2 are often faster/easier for the decoder to honor.
91         */
92        public int inSampleSize;
93
94        /**
95         * If this is non-null, the decoder will try to decode into this
96         * internal configuration. If it is null, or the request cannot be met,
97         * the decoder will try to pick the best matching config based on the
98         * system's screen depth, and characteristics of the original image such
99         * as if it has per-pixel alpha (requiring a config that also does).
100         *
101         * Image are loaded with the {@link Bitmap.Config#ARGB_8888} config by
102         * default.
103         */
104        public Bitmap.Config inPreferredConfig = Bitmap.Config.ARGB_8888;
105
106        /**
107         * If dither is true, the decoder will attempt to dither the decoded
108         * image.
109         */
110        public boolean inDither;
111
112        /**
113         * The pixel density to use for the bitmap.  This will always result
114         * in the returned bitmap having a density set for it (see
115         * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}).  In addition,
116         * if {@link #inScaled} is set (which it is by default} and this
117         * density does not match {@link #inTargetDensity}, then the bitmap
118         * will be scaled to the target density before being returned.
119         *
120         * <p>If this is 0,
121         * {@link BitmapFactory#decodeResource(Resources, int)},
122         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
123         * and {@link BitmapFactory#decodeResourceStream}
124         * will fill in the density associated with the resource.  The other
125         * functions will leave it as-is and no density will be applied.
126         *
127         * @see #inTargetDensity
128         * @see #inScreenDensity
129         * @see #inScaled
130         * @see Bitmap#setDensity(int)
131         * @see android.util.DisplayMetrics#densityDpi
132         */
133        public int inDensity;
134
135        /**
136         * The pixel density of the destination this bitmap will be drawn to.
137         * This is used in conjunction with {@link #inDensity} and
138         * {@link #inScaled} to determine if and how to scale the bitmap before
139         * returning it.
140         *
141         * <p>If this is 0,
142         * {@link BitmapFactory#decodeResource(Resources, int)},
143         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
144         * and {@link BitmapFactory#decodeResourceStream}
145         * will fill in the density associated the Resources object's
146         * DisplayMetrics.  The other
147         * functions will leave it as-is and no scaling for density will be
148         * performed.
149         *
150         * @see #inDensity
151         * @see #inScreenDensity
152         * @see #inScaled
153         * @see android.util.DisplayMetrics#densityDpi
154         */
155        public int inTargetDensity;
156
157        /**
158         * The pixel density of the actual screen that is being used.  This is
159         * purely for applications running in density compatibility code, where
160         * {@link #inTargetDensity} is actually the density the application
161         * sees rather than the real screen density.
162         *
163         * <p>By setting this, you
164         * allow the loading code to avoid scaling a bitmap that is currently
165         * in the screen density up/down to the compatibility density.  Instead,
166         * if {@link #inDensity} is the same as {@link #inScreenDensity}, the
167         * bitmap will be left as-is.  Anything using the resulting bitmap
168         * must also used {@link Bitmap#getScaledWidth(int)
169         * Bitmap.getScaledWidth} and {@link Bitmap#getScaledHeight
170         * Bitmap.getScaledHeight} to account for any different between the
171         * bitmap's density and the target's density.
172         *
173         * <p>This is never set automatically for the caller by
174         * {@link BitmapFactory} itself.  It must be explicitly set, since the
175         * caller must deal with the resulting bitmap in a density-aware way.
176         *
177         * @see #inDensity
178         * @see #inTargetDensity
179         * @see #inScaled
180         * @see android.util.DisplayMetrics#densityDpi
181         */
182        public int inScreenDensity;
183
184        /**
185         * When this flag is set, if {@link #inDensity} and
186         * {@link #inTargetDensity} are not 0, the
187         * bitmap will be scaled to match {@link #inTargetDensity} when loaded,
188         * rather than relying on the graphics system scaling it each time it
189         * is drawn to a Canvas.
190         *
191         * <p>This flag is turned on by default and should be turned off if you need
192         * a non-scaled version of the bitmap.  Nine-patch bitmaps ignore this
193         * flag and are always scaled.
194         */
195        public boolean inScaled;
196
197        /**
198         * If this is set to true, then the resulting bitmap will allocate its
199         * pixels such that they can be purged if the system needs to reclaim
200         * memory. In that instance, when the pixels need to be accessed again
201         * (e.g. the bitmap is drawn, getPixels() is called), they will be
202         * automatically re-decoded.
203         *
204         * For the re-decode to happen, the bitmap must have access to the
205         * encoded data, either by sharing a reference to the input
206         * or by making a copy of it. This distinction is controlled by
207         * inInputShareable. If this is true, then the bitmap may keep a shallow
208         * reference to the input. If this is false, then the bitmap will
209         * explicitly make a copy of the input data, and keep that. Even if
210         * sharing is allowed, the implementation may still decide to make a
211         * deep copy of the input data.
212         */
213        public boolean inPurgeable;
214
215        /**
216         * This field works in conjuction with inPurgeable. If inPurgeable is
217         * false, then this field is ignored. If inPurgeable is true, then this
218         * field determines whether the bitmap can share a reference to the
219         * input data (inputstream, array, etc.) or if it must make a deep copy.
220         */
221        public boolean inInputShareable;
222
223        /**
224         * If inPreferQualityOverSpeed is set to true, the decoder will try to
225         * decode the reconstructed image to a higher quality even at the
226         * expense of the decoding speed. Currently the field only affects JPEG
227         * decode, in the case of which a more accurate, but slightly slower,
228         * IDCT method will be used instead.
229         */
230        public boolean inPreferQualityOverSpeed;
231
232        /**
233         * The resulting width of the bitmap, set independent of the state of
234         * inJustDecodeBounds. However, if there is an error trying to decode,
235         * outWidth will be set to -1.
236         */
237
238        public int outWidth;
239
240        /**
241         * The resulting height of the bitmap, set independent of the state of
242         * inJustDecodeBounds. However, if there is an error trying to decode,
243         * outHeight will be set to -1.
244         */
245        public int outHeight;
246
247        /**
248         * If known, this string is set to the mimetype of the decoded image.
249         * If not know, or there is an error, it is set to null.
250         */
251        public String outMimeType;
252
253        /**
254         * Temp storage to use for decoding.  Suggest 16K or so.
255         */
256        public byte[] inTempStorage;
257
258        private native void requestCancel();
259
260        /**
261         * Flag to indicate that cancel has been called on this object.  This
262         * is useful if there's an intermediary that wants to first decode the
263         * bounds and then decode the image.  In that case the intermediary
264         * can check, inbetween the bounds decode and the image decode, to see
265         * if the operation is canceled.
266         */
267        public boolean mCancel;
268
269        /**
270         *  This can be called from another thread while this options object is
271         *  inside a decode... call. Calling this will notify the decoder that
272         *  it should cancel its operation. This is not guaranteed to cancel
273         *  the decode, but if it does, the decoder... operation will return
274         *  null, or if inJustDecodeBounds is true, will set outWidth/outHeight
275         *  to -1
276         */
277        public void requestCancelDecode() {
278            mCancel = true;
279            requestCancel();
280        }
281    }
282
283    /**
284     * Decode a file path into a bitmap. If the specified file name is null,
285     * or cannot be decoded into a bitmap, the function returns null.
286     *
287     * @param pathName complete path name for the file to be decoded.
288     * @param opts null-ok; Options that control downsampling and whether the
289     *             image should be completely decoded, or just is size returned.
290     * @return The decoded bitmap, or null if the image data could not be
291     *         decoded, or, if opts is non-null, if opts requested only the
292     *         size be returned (in opts.outWidth and opts.outHeight)
293     */
294    public static Bitmap decodeFile(String pathName, Options opts) {
295        Bitmap bm = null;
296        InputStream stream = null;
297        try {
298            stream = new FileInputStream(pathName);
299            bm = decodeStream(stream, null, opts);
300        } catch (Exception e) {
301            /*  do nothing.
302                If the exception happened on open, bm will be null.
303            */
304        } finally {
305            if (stream != null) {
306                try {
307                    stream.close();
308                } catch (IOException e) {
309                    // do nothing here
310                }
311            }
312        }
313        return bm;
314    }
315
316    /**
317     * Decode a file path into a bitmap. If the specified file name is null,
318     * or cannot be decoded into a bitmap, the function returns null.
319     *
320     * @param pathName complete path name for the file to be decoded.
321     * @return the resulting decoded bitmap, or null if it could not be decoded.
322     */
323    public static Bitmap decodeFile(String pathName) {
324        return decodeFile(pathName, null);
325    }
326
327    /**
328     * Decode a new Bitmap from an InputStream. This InputStream was obtained from
329     * resources, which we pass to be able to scale the bitmap accordingly.
330     */
331    public static Bitmap decodeResourceStream(Resources res, TypedValue value,
332            InputStream is, Rect pad, Options opts) {
333
334        if (opts == null) {
335            opts = new Options();
336        }
337
338        if (opts.inDensity == 0 && value != null) {
339            final int density = value.density;
340            if (density == TypedValue.DENSITY_DEFAULT) {
341                opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
342            } else if (density != TypedValue.DENSITY_NONE) {
343                opts.inDensity = density;
344            }
345        }
346
347        if (opts.inTargetDensity == 0 && res != null) {
348            opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
349        }
350
351        return decodeStream(is, pad, opts);
352    }
353
354    /**
355     * Synonym for opening the given resource and calling
356     * {@link #decodeResourceStream}.
357     *
358     * @param res   The resources object containing the image data
359     * @param id The resource id of the image data
360     * @param opts null-ok; Options that control downsampling and whether the
361     *             image should be completely decoded, or just is size returned.
362     * @return The decoded bitmap, or null if the image data could not be
363     *         decoded, or, if opts is non-null, if opts requested only the
364     *         size be returned (in opts.outWidth and opts.outHeight)
365     */
366    public static Bitmap decodeResource(Resources res, int id, Options opts) {
367        Bitmap bm = null;
368        InputStream is = null;
369
370        try {
371            final TypedValue value = new TypedValue();
372            is = res.openRawResource(id, value);
373
374            bm = decodeResourceStream(res, value, is, null, opts);
375        } catch (Exception e) {
376            /*  do nothing.
377                If the exception happened on open, bm will be null.
378                If it happened on close, bm is still valid.
379            */
380        } finally {
381            try {
382                if (is != null) is.close();
383            } catch (IOException e) {
384                // Ignore
385            }
386        }
387
388        if (bm == null && opts != null && opts.inBitmap != null) {
389            throw new IllegalArgumentException("Problem decoding into existing bitmap");
390        }
391
392        return bm;
393    }
394
395    /**
396     * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}
397     * will null Options.
398     *
399     * @param res The resources object containing the image data
400     * @param id The resource id of the image data
401     * @return The decoded bitmap, or null if the image could not be decode.
402     */
403    public static Bitmap decodeResource(Resources res, int id) {
404        return decodeResource(res, id, null);
405    }
406
407    /**
408     * Decode an immutable bitmap from the specified byte array.
409     *
410     * @param data byte array of compressed image data
411     * @param offset offset into imageData for where the decoder should begin
412     *               parsing.
413     * @param length the number of bytes, beginning at offset, to parse
414     * @param opts null-ok; Options that control downsampling and whether the
415     *             image should be completely decoded, or just is size returned.
416     * @return The decoded bitmap, or null if the image data could not be
417     *         decoded, or, if opts is non-null, if opts requested only the
418     *         size be returned (in opts.outWidth and opts.outHeight)
419     */
420    public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
421        if ((offset | length) < 0 || data.length < offset + length) {
422            throw new ArrayIndexOutOfBoundsException();
423        }
424        Bitmap bm = nativeDecodeByteArray(data, offset, length, opts);
425        if (bm == null && opts != null && opts.inBitmap != null) {
426            throw new IllegalArgumentException("Problem decoding into existing bitmap");
427        }
428        return bm;
429    }
430
431    /**
432     * Decode an immutable bitmap from the specified byte array.
433     *
434     * @param data byte array of compressed image data
435     * @param offset offset into imageData for where the decoder should begin
436     *               parsing.
437     * @param length the number of bytes, beginning at offset, to parse
438     * @return The decoded bitmap, or null if the image could not be decode.
439     */
440    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
441        return decodeByteArray(data, offset, length, null);
442    }
443
444    /**
445     * Decode an input stream into a bitmap. If the input stream is null, or
446     * cannot be used to decode a bitmap, the function returns null.
447     * The stream's position will be where ever it was after the encoded data
448     * was read.
449     *
450     * @param is The input stream that holds the raw data to be decoded into a
451     *           bitmap.
452     * @param outPadding If not null, return the padding rect for the bitmap if
453     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
454     *                   no bitmap is returned (null) then padding is
455     *                   unchanged.
456     * @param opts null-ok; Options that control downsampling and whether the
457     *             image should be completely decoded, or just is size returned.
458     * @return The decoded bitmap, or null if the image data could not be
459     *         decoded, or, if opts is non-null, if opts requested only the
460     *         size be returned (in opts.outWidth and opts.outHeight)
461     */
462    public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
463        // we don't throw in this case, thus allowing the caller to only check
464        // the cache, and not force the image to be decoded.
465        if (is == null) {
466            return null;
467        }
468
469        // we need mark/reset to work properly
470
471        if (!is.markSupported()) {
472            is = new BufferedInputStream(is, 16 * 1024);
473        }
474
475        // so we can call reset() if a given codec gives up after reading up to
476        // this many bytes. FIXME: need to find out from the codecs what this
477        // value should be.
478        is.mark(1024);
479
480        Bitmap  bm;
481
482        if (is instanceof AssetManager.AssetInputStream) {
483            bm = nativeDecodeAsset(((AssetManager.AssetInputStream) is).getAssetInt(),
484                    outPadding, opts);
485        } else {
486            // pass some temp storage down to the native code. 1024 is made up,
487            // but should be large enough to avoid too many small calls back
488            // into is.read(...) This number is not related to the value passed
489            // to mark(...) above.
490            byte [] tempStorage = null;
491            if (opts != null) tempStorage = opts.inTempStorage;
492            if (tempStorage == null) tempStorage = new byte[16 * 1024];
493            bm = nativeDecodeStream(is, tempStorage, outPadding, opts);
494        }
495        if (bm == null && opts != null && opts.inBitmap != null) {
496            throw new IllegalArgumentException("Problem decoding into existing bitmap");
497        }
498
499        return finishDecode(bm, outPadding, opts);
500    }
501
502    private static Bitmap finishDecode(Bitmap bm, Rect outPadding, Options opts) {
503        if (bm == null || opts == null) {
504            return bm;
505        }
506
507        final int density = opts.inDensity;
508        if (density == 0) {
509            return bm;
510        }
511
512        bm.setDensity(density);
513        final int targetDensity = opts.inTargetDensity;
514        if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
515            return bm;
516        }
517
518        byte[] np = bm.getNinePatchChunk();
519        final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
520        if (opts.inScaled || isNinePatch) {
521            float scale = targetDensity / (float)density;
522            // TODO: This is very inefficient and should be done in native by Skia
523            final Bitmap oldBitmap = bm;
524            bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
525                    (int) (bm.getHeight() * scale + 0.5f), true);
526            oldBitmap.recycle();
527
528            if (isNinePatch) {
529                np = nativeScaleNinePatch(np, scale, outPadding);
530                bm.setNinePatchChunk(np);
531            }
532            bm.setDensity(targetDensity);
533        }
534
535        return bm;
536    }
537
538    /**
539     * Decode an input stream into a bitmap. If the input stream is null, or
540     * cannot be used to decode a bitmap, the function returns null.
541     * The stream's position will be where ever it was after the encoded data
542     * was read.
543     *
544     * @param is The input stream that holds the raw data to be decoded into a
545     *           bitmap.
546     * @return The decoded bitmap, or null if the image data could not be decoded.
547     */
548    public static Bitmap decodeStream(InputStream is) {
549        return decodeStream(is, null, null);
550    }
551
552    /**
553     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
554     * return null. The position within the descriptor will not be changed when
555     * this returns, so the descriptor can be used again as-is.
556     *
557     * @param fd The file descriptor containing the bitmap data to decode
558     * @param outPadding If not null, return the padding rect for the bitmap if
559     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
560     *                   no bitmap is returned (null) then padding is
561     *                   unchanged.
562     * @param opts null-ok; Options that control downsampling and whether the
563     *             image should be completely decoded, or just is size returned.
564     * @return the decoded bitmap, or null
565     */
566    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
567        if (nativeIsSeekable(fd)) {
568            Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);
569            if (bm == null && opts != null && opts.inBitmap != null) {
570                throw new IllegalArgumentException("Problem decoding into existing bitmap");
571            }
572            return finishDecode(bm, outPadding, opts);
573        } else {
574            FileInputStream fis = new FileInputStream(fd);
575            try {
576                return decodeStream(fis, outPadding, opts);
577            } finally {
578                try {
579                    fis.close();
580                } catch (Throwable t) {/* ignore */}
581            }
582        }
583    }
584
585    /**
586     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
587     * return null. The position within the descriptor will not be changed when
588     * this returns, so the descriptor can be used again as is.
589     *
590     * @param fd The file descriptor containing the bitmap data to decode
591     * @return the decoded bitmap, or null
592     */
593    public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
594        return decodeFileDescriptor(fd, null, null);
595    }
596
597    /**
598     * Set the default config used for decoding bitmaps. This config is
599     * presented to the codec if the caller did not specify a preferred config
600     * in their call to decode...
601     *
602     * The default value is chosen by the system to best match the device's
603     * screen and memory constraints.
604     *
605     * @param config The preferred config for decoding bitmaps. If null, then
606     *               a suitable default is chosen by the system.
607     *
608     * @hide - only called by the browser at the moment, but should be stable
609     *   enough to expose if needed
610     */
611    public static void setDefaultConfig(Bitmap.Config config) {
612        if (config == null) {
613            // pick this for now, as historically it was our default.
614            // However, if we have a smarter algorithm, we can change this.
615            config = Bitmap.Config.RGB_565;
616        }
617        nativeSetDefaultConfig(config.nativeInt);
618    }
619
620    private static native void nativeSetDefaultConfig(int nativeConfig);
621    private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
622            Rect padding, Options opts);
623    private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
624            Rect padding, Options opts);
625    private static native Bitmap nativeDecodeAsset(int asset, Rect padding, Options opts);
626    private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
627            int length, Options opts);
628    private static native byte[] nativeScaleNinePatch(byte[] chunk, float scale, Rect pad);
629    private static native boolean nativeIsSeekable(FileDescriptor fd);
630}
631