• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package android.graphics;
18 
19 import android.content.res.AssetManager;
20 import android.content.res.Resources;
21 import android.os.MemoryFile;
22 import android.util.DisplayMetrics;
23 import android.util.TypedValue;
24 
25 import java.io.BufferedInputStream;
26 import java.io.FileDescriptor;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 
31 /**
32  * Creates Bitmap objects from various sources, including files, streams,
33  * and byte-arrays.
34  */
35 public class BitmapFactory {
36     public static class Options {
37         /**
38          * Create a default Options object, which if left unchanged will give
39          * the same result from the decoder as if null were passed.
40          */
Options()41         public Options() {
42             inDither = true;
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 attempt to dither the decoded
77          * image.
78          */
79         public boolean inDither;
80 
81         /**
82          * The pixel density to use for the bitmap.  This will always result
83          * in the returned bitmap having a density set for it (see
84          * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)).  In addition,
85          * if {@link #inScaled} is set (which it is by default} and this
86          * density does not match {@link #inTargetDensity}, then the bitmap
87          * will be scaled to the target density before being returned.
88          *
89          * <p>If this is 0,
90          * {@link BitmapFactory#decodeResource(Resources, int)},
91          * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
92          * and {@link BitmapFactory#decodeResourceStream}
93          * will fill in the density associated with the resource.  The other
94          * functions will leave it as-is and no density will be applied.
95          *
96          * @see #inTargetDensity
97          * @see #inScreenDensity
98          * @see #inScaled
99          * @see Bitmap#setDensity(int)
100          * @see android.util.DisplayMetrics#densityDpi
101          */
102         public int inDensity;
103 
104         /**
105          * The pixel density of the destination this bitmap will be drawn to.
106          * This is used in conjunction with {@link #inDensity} and
107          * {@link #inScaled} to determine if and how to scale the bitmap before
108          * returning it.
109          *
110          * <p>If this is 0,
111          * {@link BitmapFactory#decodeResource(Resources, int)},
112          * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
113          * and {@link BitmapFactory#decodeResourceStream}
114          * will fill in the density associated the Resources object's
115          * DisplayMetrics.  The other
116          * functions will leave it as-is and no scaling for density will be
117          * performed.
118          *
119          * @see #inDensity
120          * @see #inScreenDensity
121          * @see #inScaled
122          * @see android.util.DisplayMetrics#densityDpi
123          */
124         public int inTargetDensity;
125 
126         /**
127          * The pixel density of the actual screen that is being used.  This is
128          * purely for applications running in density compatibility code, where
129          * {@link #inTargetDensity} is actually the density the application
130          * sees rather than the real screen density.
131          *
132          * <p>By setting this, you
133          * allow the loading code to avoid scaling a bitmap that is currently
134          * in the screen density up/down to the compatibility density.  Instead,
135          * if {@link #inDensity} is the same as {@link #inScreenDensity}, the
136          * bitmap will be left as-is.  Anything using the resulting bitmap
137          * must also used {@link Bitmap#getScaledWidth(int)
138          * Bitmap.getScaledWidth} and {@link Bitmap#getScaledHeight
139          * Bitmap.getScaledHeight} to account for any different between the
140          * bitmap's density and the target's density.
141          *
142          * <p>This is never set automatically for the caller by
143          * {@link BitmapFactory} itself.  It must be explicitly set, since the
144          * caller must deal with the resulting bitmap in a density-aware way.
145          *
146          * @see #inDensity
147          * @see #inTargetDensity
148          * @see #inScaled
149          * @see android.util.DisplayMetrics#densityDpi
150          */
151         public int inScreenDensity;
152 
153         /**
154          * When this flag is set, if {@link #inDensity} and
155          * {@link #inTargetDensity} are not 0, the
156          * bitmap will be scaled to match {@link #inTargetDensity} when loaded,
157          * rather than relying on the graphics system scaling it each time it
158          * is drawn to a Canvas.
159          *
160          * <p>This flag is turned on by default and should be turned off if you need
161          * a non-scaled version of the bitmap.  Nine-patch bitmaps ignore this
162          * flag and are always scaled.
163          */
164         public boolean inScaled;
165 
166         /**
167          * If this is set to true, then the resulting bitmap will allocate its
168          * pixels such that they can be purged if the system needs to reclaim
169          * memory. In that instance, when the pixels need to be accessed again
170          * (e.g. the bitmap is drawn, getPixels() is called), they will be
171          * automatically re-decoded.
172          *
173          * For the re-decode to happen, the bitmap must have access to the
174          * encoded data, either by sharing a reference to the input
175          * or by making a copy of it. This distinction is controlled by
176          * inInputShareable. If this is true, then the bitmap may keep a shallow
177          * reference to the input. If this is false, then the bitmap will
178          * explicitly make a copy of the input data, and keep that. Even if
179          * sharing is allowed, the implementation may still decide to make a
180          * deep copy of the input data.
181          */
182         public boolean inPurgeable;
183 
184         /**
185          * This field works in conjuction with inPurgeable. If inPurgeable is
186          * false, then this field is ignored. If inPurgeable is true, then this
187          * field determines whether the bitmap can share a reference to the
188          * input data (inputstream, array, etc.) or if it must make a deep copy.
189          */
190         public boolean inInputShareable;
191 
192         /**
193          * Normally bitmap allocations count against the dalvik heap, which
194          * means they help trigger GCs when a lot have been allocated. However,
195          * in rare cases, the caller may want to allocate the bitmap outside of
196          * that heap. To request that, set inNativeAlloc to true. In these
197          * rare instances, it is solely up to the caller to ensure that OOM is
198          * managed explicitly by calling bitmap.recycle() as soon as such a
199          * bitmap is no longer needed.
200          *
201          * @hide pending API council approval
202          */
203         public boolean inNativeAlloc;
204 
205         /**
206          * The resulting width of the bitmap, set independent of the state of
207          * inJustDecodeBounds. However, if there is an error trying to decode,
208          * outWidth will be set to -1.
209          */
210         public int outWidth;
211 
212         /**
213          * The resulting height of the bitmap, set independent of the state of
214          * inJustDecodeBounds. However, if there is an error trying to decode,
215          * outHeight will be set to -1.
216          */
217         public int outHeight;
218 
219         /**
220          * If known, this string is set to the mimetype of the decoded image.
221          * If not know, or there is an error, it is set to null.
222          */
223         public String outMimeType;
224 
225         /**
226          * Temp storage to use for decoding.  Suggest 16K or so.
227          */
228         public byte[] inTempStorage;
229 
requestCancel()230         private native void requestCancel();
231 
232         /**
233          * Flag to indicate that cancel has been called on this object.  This
234          * is useful if there's an intermediary that wants to first decode the
235          * bounds and then decode the image.  In that case the intermediary
236          * can check, inbetween the bounds decode and the image decode, to see
237          * if the operation is canceled.
238          */
239         public boolean mCancel;
240 
241         /**
242          *  This can be called from another thread while this options object is
243          *  inside a decode... call. Calling this will notify the decoder that
244          *  it should cancel its operation. This is not guaranteed to cancel
245          *  the decode, but if it does, the decoder... operation will return
246          *  null, or if inJustDecodeBounds is true, will set outWidth/outHeight
247          *  to -1
248          */
requestCancelDecode()249         public void requestCancelDecode() {
250             mCancel = true;
251             requestCancel();
252         }
253     }
254 
255     /**
256      * Decode a file path into a bitmap. If the specified file name is null,
257      * or cannot be decoded into a bitmap, the function returns null.
258      *
259      * @param pathName complete path name for the file to be decoded.
260      * @param opts null-ok; Options that control downsampling and whether the
261      *             image should be completely decoded, or just is size returned.
262      * @return The decoded bitmap, or null if the image data could not be
263      *         decoded, or, if opts is non-null, if opts requested only the
264      *         size be returned (in opts.outWidth and opts.outHeight)
265      */
decodeFile(String pathName, Options opts)266     public static Bitmap decodeFile(String pathName, Options opts) {
267         Bitmap bm = null;
268         InputStream stream = null;
269         try {
270             stream = new FileInputStream(pathName);
271             bm = decodeStream(stream, null, opts);
272         } catch (Exception e) {
273             /*  do nothing.
274                 If the exception happened on open, bm will be null.
275             */
276         } finally {
277             if (stream != null) {
278                 try {
279                     stream.close();
280                 } catch (IOException e) {
281                     // do nothing here
282                 }
283             }
284         }
285         return bm;
286     }
287 
288     /**
289      * Decode a file path into a bitmap. If the specified file name is null,
290      * or cannot be decoded into a bitmap, the function returns null.
291      *
292      * @param pathName complete path name for the file to be decoded.
293      * @return the resulting decoded bitmap, or null if it could not be decoded.
294      */
decodeFile(String pathName)295     public static Bitmap decodeFile(String pathName) {
296         return decodeFile(pathName, null);
297     }
298 
299     /**
300      * Decode a new Bitmap from an InputStream. This InputStream was obtained from
301      * resources, which we pass to be able to scale the bitmap accordingly.
302      */
decodeResourceStream(Resources res, TypedValue value, InputStream is, Rect pad, Options opts)303     public static Bitmap decodeResourceStream(Resources res, TypedValue value,
304             InputStream is, Rect pad, Options opts) {
305 
306         if (opts == null) {
307             opts = new Options();
308         }
309 
310         if (opts.inDensity == 0 && value != null) {
311             final int density = value.density;
312             if (density == TypedValue.DENSITY_DEFAULT) {
313                 opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
314             } else if (density != TypedValue.DENSITY_NONE) {
315                 opts.inDensity = density;
316             }
317         }
318 
319         if (opts.inTargetDensity == 0 && res != null) {
320             opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
321         }
322 
323         return decodeStream(is, pad, opts);
324     }
325 
326     /**
327      * Synonym for opening the given resource and calling
328      * {@link #decodeResourceStream}.
329      *
330      * @param res   The resources object containing the image data
331      * @param id The resource id of the image data
332      * @param opts null-ok; Options that control downsampling and whether the
333      *             image should be completely decoded, or just is size returned.
334      * @return The decoded bitmap, or null if the image data could not be
335      *         decoded, or, if opts is non-null, if opts requested only the
336      *         size be returned (in opts.outWidth and opts.outHeight)
337      */
decodeResource(Resources res, int id, Options opts)338     public static Bitmap decodeResource(Resources res, int id, Options opts) {
339         Bitmap bm = null;
340         InputStream is = null;
341 
342         try {
343             final TypedValue value = new TypedValue();
344             is = res.openRawResource(id, value);
345 
346             bm = decodeResourceStream(res, value, is, null, opts);
347         } catch (Exception e) {
348             /*  do nothing.
349                 If the exception happened on open, bm will be null.
350                 If it happened on close, bm is still valid.
351             */
352         } finally {
353             try {
354                 if (is != null) is.close();
355             } catch (IOException e) {
356                 // Ignore
357             }
358         }
359 
360         return bm;
361     }
362 
363     /**
364      * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}
365      * will null Options.
366      *
367      * @param res The resources object containing the image data
368      * @param id The resource id of the image data
369      * @return The decoded bitmap, or null if the image could not be decode.
370      */
decodeResource(Resources res, int id)371     public static Bitmap decodeResource(Resources res, int id) {
372         return decodeResource(res, id, null);
373     }
374 
375     /**
376      * Decode an immutable bitmap from the specified byte array.
377      *
378      * @param data byte array of compressed image data
379      * @param offset offset into imageData for where the decoder should begin
380      *               parsing.
381      * @param length the number of bytes, beginning at offset, to parse
382      * @param opts null-ok; Options that control downsampling and whether the
383      *             image should be completely decoded, or just is size returned.
384      * @return The decoded bitmap, or null if the image data could not be
385      *         decoded, or, if opts is non-null, if opts requested only the
386      *         size be returned (in opts.outWidth and opts.outHeight)
387      */
decodeByteArray(byte[] data, int offset, int length, Options opts)388     public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
389         if ((offset | length) < 0 || data.length < offset + length) {
390             throw new ArrayIndexOutOfBoundsException();
391         }
392         return nativeDecodeByteArray(data, offset, length, opts);
393     }
394 
395     /**
396      * Decode an immutable bitmap from the specified byte array.
397      *
398      * @param data byte array of compressed image data
399      * @param offset offset into imageData for where the decoder should begin
400      *               parsing.
401      * @param length the number of bytes, beginning at offset, to parse
402      * @return The decoded bitmap, or null if the image could not be decode.
403      */
decodeByteArray(byte[] data, int offset, int length)404     public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
405         return decodeByteArray(data, offset, length, null);
406     }
407 
408     /**
409      * Decode an input stream into a bitmap. If the input stream is null, or
410      * cannot be used to decode a bitmap, the function returns null.
411      * The stream's position will be where ever it was after the encoded data
412      * was read.
413      *
414      * @param is The input stream that holds the raw data to be decoded into a
415      *           bitmap.
416      * @param outPadding If not null, return the padding rect for the bitmap if
417      *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
418      *                   no bitmap is returned (null) then padding is
419      *                   unchanged.
420      * @param opts null-ok; Options that control downsampling and whether the
421      *             image should be completely decoded, or just is size returned.
422      * @return The decoded bitmap, or null if the image data could not be
423      *         decoded, or, if opts is non-null, if opts requested only the
424      *         size be returned (in opts.outWidth and opts.outHeight)
425      */
decodeStream(InputStream is, Rect outPadding, Options opts)426     public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
427         // we don't throw in this case, thus allowing the caller to only check
428         // the cache, and not force the image to be decoded.
429         if (is == null) {
430             return null;
431         }
432 
433         // we need mark/reset to work properly
434 
435         if (!is.markSupported()) {
436             is = new BufferedInputStream(is, 16 * 1024);
437         }
438 
439         // so we can call reset() if a given codec gives up after reading up to
440         // this many bytes. FIXME: need to find out from the codecs what this
441         // value should be.
442         is.mark(1024);
443 
444         Bitmap  bm;
445 
446         if (is instanceof AssetManager.AssetInputStream) {
447             bm = nativeDecodeAsset(((AssetManager.AssetInputStream) is).getAssetInt(),
448                     outPadding, opts);
449         } else {
450             // pass some temp storage down to the native code. 1024 is made up,
451             // but should be large enough to avoid too many small calls back
452             // into is.read(...) This number is not related to the value passed
453             // to mark(...) above.
454             byte [] tempStorage = null;
455             if (opts != null)
456                 tempStorage = opts.inTempStorage;
457             if (tempStorage == null)
458                 tempStorage = new byte[16 * 1024];
459             bm = nativeDecodeStream(is, tempStorage, outPadding, opts);
460         }
461 
462         return finishDecode(bm, outPadding, opts);
463     }
464 
finishDecode(Bitmap bm, Rect outPadding, Options opts)465     private static Bitmap finishDecode(Bitmap bm, Rect outPadding, Options opts) {
466         if (bm == null || opts == null) {
467             return bm;
468         }
469 
470         final int density = opts.inDensity;
471         if (density == 0) {
472             return bm;
473         }
474 
475         bm.setDensity(density);
476         final int targetDensity = opts.inTargetDensity;
477         if (targetDensity == 0 || density == targetDensity
478                 || density == opts.inScreenDensity) {
479             return bm;
480         }
481 
482         byte[] np = bm.getNinePatchChunk();
483         final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
484         if (opts.inScaled || isNinePatch) {
485             float scale = targetDensity / (float)density;
486             // TODO: This is very inefficient and should be done in native by Skia
487             final Bitmap oldBitmap = bm;
488             bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
489                     (int) (bm.getHeight() * scale + 0.5f), true);
490             oldBitmap.recycle();
491 
492             if (isNinePatch) {
493                 np = nativeScaleNinePatch(np, scale, outPadding);
494                 bm.setNinePatchChunk(np);
495             }
496             bm.setDensity(targetDensity);
497         }
498 
499         return bm;
500     }
501 
502     /**
503      * Decode an input stream into a bitmap. If the input stream is null, or
504      * cannot be used to decode a bitmap, the function returns null.
505      * The stream's position will be where ever it was after the encoded data
506      * was read.
507      *
508      * @param is The input stream that holds the raw data to be decoded into a
509      *           bitmap.
510      * @return The decoded bitmap, or null if the image data could not be
511      *         decoded, or, if opts is non-null, if opts requested only the
512      *         size be returned (in opts.outWidth and opts.outHeight)
513      */
decodeStream(InputStream is)514     public static Bitmap decodeStream(InputStream is) {
515         return decodeStream(is, null, null);
516     }
517 
518     /**
519      * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
520      * return null. The position within the descriptor will not be changed when
521      * this returns, so the descriptor can be used again as-is.
522      *
523      * @param fd The file descriptor containing the bitmap data to decode
524      * @param outPadding If not null, return the padding rect for the bitmap if
525      *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
526      *                   no bitmap is returned (null) then padding is
527      *                   unchanged.
528      * @param opts null-ok; Options that control downsampling and whether the
529      *             image should be completely decoded, or just is size returned.
530      * @return the decoded bitmap, or null
531      */
decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)532     public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
533         try {
534             if (MemoryFile.isMemoryFile(fd)) {
535                 int mappedlength = MemoryFile.getMappedSize(fd);
536                 MemoryFile file = new MemoryFile(fd, mappedlength, "r");
537                 InputStream is = file.getInputStream();
538                 Bitmap bm = decodeStream(is, outPadding, opts);
539                 return finishDecode(bm, outPadding, opts);
540             }
541         } catch (IOException ex) {
542             // invalid filedescriptor, no need to call nativeDecodeFileDescriptor()
543             return null;
544         }
545         Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);
546         return finishDecode(bm, outPadding, opts);
547     }
548 
549     /**
550      * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
551      * return null. The position within the descriptor will not be changed when
552      * this returns, so the descriptor can be used again as is.
553      *
554      * @param fd The file descriptor containing the bitmap data to decode
555      * @return the decoded bitmap, or null
556      */
decodeFileDescriptor(FileDescriptor fd)557     public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
558         return decodeFileDescriptor(fd, null, null);
559     }
560 
nativeDecodeStream(InputStream is, byte[] storage, Rect padding, Options opts)561     private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
562             Rect padding, Options opts);
nativeDecodeFileDescriptor(FileDescriptor fd, Rect padding, Options opts)563     private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
564             Rect padding, Options opts);
nativeDecodeAsset(int asset, Rect padding, Options opts)565     private static native Bitmap nativeDecodeAsset(int asset, Rect padding, Options opts);
nativeDecodeByteArray(byte[] data, int offset, int length, Options opts)566     private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
567             int length, Options opts);
nativeScaleNinePatch(byte[] chunk, float scale, Rect pad)568     private static native byte[] nativeScaleNinePatch(byte[] chunk, float scale, Rect pad);
569 }
570 
571