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 static android.graphics.BitmapFactory.Options.validate;
20 
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.compat.annotation.UnsupportedAppUsage;
24 import android.content.res.AssetManager;
25 import android.content.res.Resources;
26 import android.os.Trace;
27 import android.util.DisplayMetrics;
28 import android.util.Log;
29 import android.util.TypedValue;
30 
31 import java.io.FileDescriptor;
32 import java.io.FileInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 
36 /**
37  * Creates Bitmap objects from various sources, including files, streams,
38  * and byte-arrays.
39  */
40 public class BitmapFactory {
41     private static final int DECODE_BUFFER_SIZE = 16 * 1024;
42 
43     public static class Options {
44         /**
45          * Create a default Options object, which if left unchanged will give
46          * the same result from the decoder as if null were passed.
47          */
Options()48         public Options() {
49             inScaled = true;
50             inPremultiplied = true;
51         }
52 
53         /**
54          * If set, decode methods that take the Options object will attempt to
55          * reuse this bitmap when loading content. If the decode operation
56          * cannot use this bitmap, the decode method will throw an
57          * {@link java.lang.IllegalArgumentException}. The
58          * current implementation necessitates that the reused bitmap be
59          * mutable, and the resulting reused bitmap will continue to remain
60          * mutable even when decoding a resource which would normally result in
61          * an immutable bitmap.</p>
62          *
63          * <p>You should still always use the returned Bitmap of the decode
64          * method and not assume that reusing the bitmap worked, due to the
65          * constraints outlined above and failure situations that can occur.
66          * Checking whether the return value matches the value of the inBitmap
67          * set in the Options structure will indicate if the bitmap was reused,
68          * but in all cases you should use the Bitmap returned by the decoding
69          * function to ensure that you are using the bitmap that was used as the
70          * decode destination.</p>
71          *
72          * <h3>Usage with BitmapFactory</h3>
73          *
74          * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, any
75          * mutable bitmap can be reused by {@link BitmapFactory} to decode any
76          * other bitmaps as long as the resulting {@link Bitmap#getByteCount()
77          * byte count} of the decoded bitmap is less than or equal to the {@link
78          * Bitmap#getAllocationByteCount() allocated byte count} of the reused
79          * bitmap. This can be because the intrinsic size is smaller, or its
80          * size post scaling (for density / sample size) is smaller.</p>
81          *
82          * <p class="note">Prior to {@link android.os.Build.VERSION_CODES#KITKAT}
83          * additional constraints apply: The image being decoded (whether as a
84          * resource or as a stream) must be in jpeg or png format. Only equal
85          * sized bitmaps are supported, with {@link #inSampleSize} set to 1.
86          * Additionally, the {@link android.graphics.Bitmap.Config
87          * configuration} of the reused bitmap will override the setting of
88          * {@link #inPreferredConfig}, if set.</p>
89          *
90          * <h3>Usage with BitmapRegionDecoder</h3>
91          *
92          * <p>BitmapRegionDecoder will draw its requested content into the Bitmap
93          * provided, clipping if the output content size (post scaling) is larger
94          * than the provided Bitmap. The provided Bitmap's width, height, and
95          * {@link Bitmap.Config} will not be changed.
96          *
97          * <p class="note">BitmapRegionDecoder support for {@link #inBitmap} was
98          * introduced in {@link android.os.Build.VERSION_CODES#JELLY_BEAN}. All
99          * formats supported by BitmapRegionDecoder support Bitmap reuse via
100          * {@link #inBitmap}.</p>
101          *
102          * @see Bitmap#reconfigure(int,int, android.graphics.Bitmap.Config)
103          */
104         public Bitmap inBitmap;
105 
106         /**
107          * If set, decode methods will always return a mutable Bitmap instead of
108          * an immutable one. This can be used for instance to programmatically apply
109          * effects to a Bitmap loaded through BitmapFactory.
110          * <p>Can not be set simultaneously with inPreferredConfig =
111          * {@link android.graphics.Bitmap.Config#HARDWARE},
112          * because hardware bitmaps are always immutable.
113          */
114         @SuppressWarnings({"UnusedDeclaration"}) // used in native code
115         public boolean inMutable;
116 
117         /**
118          * If set to true, the decoder will return null (no bitmap), but
119          * the <code>out...</code> fields will still be set, allowing the caller to
120          * query the bitmap without having to allocate the memory for its pixels.
121          */
122         public boolean inJustDecodeBounds;
123 
124         /**
125          * If set to a value > 1, requests the decoder to subsample the original
126          * image, returning a smaller image to save memory. The sample size is
127          * the number of pixels in either dimension that correspond to a single
128          * pixel in the decoded bitmap. For example, inSampleSize == 4 returns
129          * an image that is 1/4 the width/height of the original, and 1/16 the
130          * number of pixels. Any value <= 1 is treated the same as 1. Note: the
131          * decoder uses a final value based on powers of 2, any other value will
132          * be rounded down to the nearest power of 2.
133          */
134         public int inSampleSize;
135 
136         /**
137          * If this is non-null, the decoder will try to decode into this
138          * internal configuration. If it is null, or the request cannot be met,
139          * the decoder will try to pick the best matching config based on the
140          * system's screen depth, and characteristics of the original image such
141          * as if it has per-pixel alpha (requiring a config that also does).
142          *
143          * Image are loaded with the {@link Bitmap.Config#ARGB_8888} config by
144          * default.
145          */
146         public Bitmap.Config inPreferredConfig = Bitmap.Config.ARGB_8888;
147 
148         /**
149          * <p>If this is non-null, the decoder will try to decode into this
150          * color space. If it is null, or the request cannot be met,
151          * the decoder will pick either the color space embedded in the image
152          * or the color space best suited for the requested image configuration
153          * (for instance {@link ColorSpace.Named#SRGB sRGB} for
154          * {@link Bitmap.Config#ARGB_8888} configuration and
155          * {@link ColorSpace.Named#EXTENDED_SRGB EXTENDED_SRGB} for
156          * {@link Bitmap.Config#RGBA_F16}).</p>
157          *
158          * <p class="note">Only {@link ColorSpace.Model#RGB} color spaces are
159          * currently supported. An <code>IllegalArgumentException</code> will
160          * be thrown by the decode methods when setting a non-RGB color space
161          * such as {@link ColorSpace.Named#CIE_LAB Lab}.</p>
162          *
163          * <p class="note">The specified color space's transfer function must be
164          * an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}. An
165          * <code>IllegalArgumentException</code> will be thrown by the decode methods
166          * if calling {@link ColorSpace.Rgb#getTransferParameters()} on the
167          * specified color space returns null.</p>
168          *
169          * <p>After decode, the bitmap's color space is stored in
170          * {@link #outColorSpace}.</p>
171          */
172         public ColorSpace inPreferredColorSpace = null;
173 
174         /**
175          * If true (which is the default), the resulting bitmap will have its
176          * color channels pre-multipled by the alpha channel.
177          *
178          * <p>This should NOT be set to false for images to be directly drawn by
179          * the view system or through a {@link Canvas}. The view system and
180          * {@link Canvas} assume all drawn images are pre-multiplied to simplify
181          * draw-time blending, and will throw a RuntimeException when
182          * un-premultiplied are drawn.</p>
183          *
184          * <p>This is likely only useful if you want to manipulate raw encoded
185          * image data, e.g. with RenderScript or custom OpenGL.</p>
186          *
187          * <p>This does not affect bitmaps without an alpha channel.</p>
188          *
189          * <p>Setting this flag to false while setting {@link #inScaled} to true
190          * may result in incorrect colors.</p>
191          *
192          * @see Bitmap#hasAlpha()
193          * @see Bitmap#isPremultiplied()
194          * @see #inScaled
195          */
196         public boolean inPremultiplied;
197 
198         /**
199          * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, this is
200          * ignored.
201          *
202          * In {@link android.os.Build.VERSION_CODES#M} and below, if dither is
203          * true, the decoder will attempt to dither the decoded image.
204          */
205         public boolean inDither;
206 
207         /**
208          * The pixel density to use for the bitmap.  This will always result
209          * in the returned bitmap having a density set for it (see
210          * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}).  In addition,
211          * if {@link #inScaled} is set (which it is by default} and this
212          * density does not match {@link #inTargetDensity}, then the bitmap
213          * will be scaled to the target density before being returned.
214          *
215          * <p>If this is 0,
216          * {@link BitmapFactory#decodeResource(Resources, int)},
217          * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
218          * and {@link BitmapFactory#decodeResourceStream}
219          * will fill in the density associated with the resource.  The other
220          * functions will leave it as-is and no density will be applied.
221          *
222          * @see #inTargetDensity
223          * @see #inScreenDensity
224          * @see #inScaled
225          * @see Bitmap#setDensity(int)
226          * @see android.util.DisplayMetrics#densityDpi
227          */
228         public int inDensity;
229 
230         /**
231          * The pixel density of the destination this bitmap will be drawn to.
232          * This is used in conjunction with {@link #inDensity} and
233          * {@link #inScaled} to determine if and how to scale the bitmap before
234          * returning it.
235          *
236          * <p>If this is 0,
237          * {@link BitmapFactory#decodeResource(Resources, int)},
238          * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
239          * and {@link BitmapFactory#decodeResourceStream}
240          * will fill in the density associated the Resources object's
241          * DisplayMetrics.  The other
242          * functions will leave it as-is and no scaling for density will be
243          * performed.
244          *
245          * @see #inDensity
246          * @see #inScreenDensity
247          * @see #inScaled
248          * @see android.util.DisplayMetrics#densityDpi
249          */
250         public int inTargetDensity;
251 
252         /**
253          * The pixel density of the actual screen that is being used.  This is
254          * purely for applications running in density compatibility code, where
255          * {@link #inTargetDensity} is actually the density the application
256          * sees rather than the real screen density.
257          *
258          * <p>By setting this, you
259          * allow the loading code to avoid scaling a bitmap that is currently
260          * in the screen density up/down to the compatibility density.  Instead,
261          * if {@link #inDensity} is the same as {@link #inScreenDensity}, the
262          * bitmap will be left as-is.  Anything using the resulting bitmap
263          * must also used {@link Bitmap#getScaledWidth(int)
264          * Bitmap.getScaledWidth} and {@link Bitmap#getScaledHeight
265          * Bitmap.getScaledHeight} to account for any different between the
266          * bitmap's density and the target's density.
267          *
268          * <p>This is never set automatically for the caller by
269          * {@link BitmapFactory} itself.  It must be explicitly set, since the
270          * caller must deal with the resulting bitmap in a density-aware way.
271          *
272          * @see #inDensity
273          * @see #inTargetDensity
274          * @see #inScaled
275          * @see android.util.DisplayMetrics#densityDpi
276          */
277         public int inScreenDensity;
278 
279         /**
280          * When this flag is set, if {@link #inDensity} and
281          * {@link #inTargetDensity} are not 0, the
282          * bitmap will be scaled to match {@link #inTargetDensity} when loaded,
283          * rather than relying on the graphics system scaling it each time it
284          * is drawn to a Canvas.
285          *
286          * <p>BitmapRegionDecoder ignores this flag, and will not scale output
287          * based on density. (though {@link #inSampleSize} is supported)</p>
288          *
289          * <p>This flag is turned on by default and should be turned off if you need
290          * a non-scaled version of the bitmap.  Nine-patch bitmaps ignore this
291          * flag and are always scaled.
292          *
293          * <p>If {@link #inPremultiplied} is set to false, and the image has alpha,
294          * setting this flag to true may result in incorrect colors.
295          */
296         public boolean inScaled;
297 
298         /**
299          * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this is
300          * ignored.
301          *
302          * In {@link android.os.Build.VERSION_CODES#KITKAT} and below, if this
303          * is set to true, then the resulting bitmap will allocate its
304          * pixels such that they can be purged if the system needs to reclaim
305          * memory. In that instance, when the pixels need to be accessed again
306          * (e.g. the bitmap is drawn, getPixels() is called), they will be
307          * automatically re-decoded.
308          *
309          * <p>For the re-decode to happen, the bitmap must have access to the
310          * encoded data, either by sharing a reference to the input
311          * or by making a copy of it. This distinction is controlled by
312          * inInputShareable. If this is true, then the bitmap may keep a shallow
313          * reference to the input. If this is false, then the bitmap will
314          * explicitly make a copy of the input data, and keep that. Even if
315          * sharing is allowed, the implementation may still decide to make a
316          * deep copy of the input data.</p>
317          *
318          * <p>While inPurgeable can help avoid big Dalvik heap allocations (from
319          * API level 11 onward), it sacrifices performance predictability since any
320          * image that the view system tries to draw may incur a decode delay which
321          * can lead to dropped frames. Therefore, most apps should avoid using
322          * inPurgeable to allow for a fast and fluid UI. To minimize Dalvik heap
323          * allocations use the {@link #inBitmap} flag instead.</p>
324          *
325          * <p class="note"><strong>Note:</strong> This flag is ignored when used
326          * with {@link #decodeResource(Resources, int,
327          * android.graphics.BitmapFactory.Options)} or {@link #decodeFile(String,
328          * android.graphics.BitmapFactory.Options)}.</p>
329          */
330         @Deprecated
331         public boolean inPurgeable;
332 
333         /**
334          * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this is
335          * ignored.
336          *
337          * In {@link android.os.Build.VERSION_CODES#KITKAT} and below, this
338          * field works in conjuction with inPurgeable. If inPurgeable is false,
339          * then this field is ignored. If inPurgeable is true, then this field
340          * determines whether the bitmap can share a reference to the input
341          * data (inputstream, array, etc.) or if it must make a deep copy.
342          */
343         @Deprecated
344         public boolean inInputShareable;
345 
346         /**
347          * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, this is
348          * ignored.  The output will always be high quality.
349          *
350          * In {@link android.os.Build.VERSION_CODES#M} and below, if
351          * inPreferQualityOverSpeed is set to true, the decoder will try to
352          * decode the reconstructed image to a higher quality even at the
353          * expense of the decoding speed. Currently the field only affects JPEG
354          * decode, in the case of which a more accurate, but slightly slower,
355          * IDCT method will be used instead.
356          */
357         @Deprecated
358         public boolean inPreferQualityOverSpeed;
359 
360         /**
361          * The resulting width of the bitmap. If {@link #inJustDecodeBounds} is
362          * set to false, this will be width of the output bitmap after any
363          * scaling is applied. If true, it will be the width of the input image
364          * without any accounting for scaling.
365          *
366          * <p>outWidth will be set to -1 if there is an error trying to decode.</p>
367          */
368         public int outWidth;
369 
370         /**
371          * The resulting height of the bitmap. If {@link #inJustDecodeBounds} is
372          * set to false, this will be height of the output bitmap after any
373          * scaling is applied. If true, it will be the height of the input image
374          * without any accounting for scaling.
375          *
376          * <p>outHeight will be set to -1 if there is an error trying to decode.</p>
377          */
378         public int outHeight;
379 
380         /**
381          * If known, this string is set to the mimetype of the decoded image.
382          * If not known, or there is an error, it is set to null.
383          */
384         public String outMimeType;
385 
386         /**
387          * If known, the config the decoded bitmap will have.
388          * If not known, or there is an error, it is set to null.
389          */
390         public Bitmap.Config outConfig;
391 
392         /**
393          * If known, the color space the decoded bitmap will have. Note that the
394          * output color space is not guaranteed to be the color space the bitmap
395          * is encoded with. If not known (when the config is
396          * {@link Bitmap.Config#ALPHA_8} for instance), or there is an error,
397          * it is set to null.
398          */
399         public ColorSpace outColorSpace;
400 
401         /**
402          * Temp storage to use for decoding.  Suggest 16K or so.
403          */
404         public byte[] inTempStorage;
405 
406         /**
407          * @deprecated As of {@link android.os.Build.VERSION_CODES#N}, see
408          * comments on {@link #requestCancelDecode()}.
409          *
410          * Flag to indicate that cancel has been called on this object.  This
411          * is useful if there's an intermediary that wants to first decode the
412          * bounds and then decode the image.  In that case the intermediary
413          * can check, inbetween the bounds decode and the image decode, to see
414          * if the operation is canceled.
415          */
416         @Deprecated
417         public boolean mCancel;
418 
419         /**
420          *  @deprecated As of {@link android.os.Build.VERSION_CODES#N}, this
421          *  will not affect the decode, though it will still set mCancel.
422          *
423          *  In {@link android.os.Build.VERSION_CODES#M} and below, if this can
424          *  be called from another thread while this options object is inside
425          *  a decode... call. Calling this will notify the decoder that it
426          *  should cancel its operation. This is not guaranteed to cancel the
427          *  decode, but if it does, the decoder... operation will return null,
428          *  or if inJustDecodeBounds is true, will set outWidth/outHeight
429          *  to -1
430          */
431         @Deprecated
requestCancelDecode()432         public void requestCancelDecode() {
433             mCancel = true;
434         }
435 
validate(Options opts)436         static void validate(Options opts) {
437             if (opts == null) return;
438 
439             if (opts.inBitmap != null) {
440                 if (opts.inBitmap.getConfig() == Bitmap.Config.HARDWARE) {
441                     throw new IllegalArgumentException(
442                             "Bitmaps with Config.HARDWARE are always immutable");
443                 }
444                 if (opts.inBitmap.isRecycled()) {
445                     throw new IllegalArgumentException(
446                             "Cannot reuse a recycled Bitmap");
447                 }
448             }
449 
450             if (opts.inMutable && opts.inPreferredConfig == Bitmap.Config.HARDWARE) {
451                 throw new IllegalArgumentException("Bitmaps with Config.HARDWARE cannot be " +
452                         "decoded into - they are immutable");
453             }
454 
455             if (opts.inPreferredColorSpace != null) {
456                 if (!(opts.inPreferredColorSpace instanceof ColorSpace.Rgb)) {
457                     throw new IllegalArgumentException("The destination color space must use the " +
458                             "RGB color model");
459                 }
460                 if (((ColorSpace.Rgb) opts.inPreferredColorSpace).getTransferParameters() == null) {
461                     throw new IllegalArgumentException("The destination color space must use an " +
462                             "ICC parametric transfer function");
463                 }
464             }
465         }
466 
467         /**
468          *  Helper for passing inBitmap's native pointer to native.
469          */
nativeInBitmap(Options opts)470         static long nativeInBitmap(Options opts) {
471             if (opts == null || opts.inBitmap == null) {
472                 return 0;
473             }
474 
475             return opts.inBitmap.getNativeInstance();
476         }
477 
478         /**
479          *  Helper for passing SkColorSpace pointer to native.
480          *
481          *  @throws IllegalArgumentException if the ColorSpace is not Rgb or does
482          *          not have TransferParameters.
483          */
nativeColorSpace(Options opts)484         static long nativeColorSpace(Options opts) {
485             if (opts == null || opts.inPreferredColorSpace == null) {
486                 return 0;
487             }
488 
489             return opts.inPreferredColorSpace.getNativeInstance();
490         }
491 
492     }
493 
494     /**
495      * Decode a file path into a bitmap. If the specified file name is null,
496      * or cannot be decoded into a bitmap, the function returns null.
497      *
498      * @param pathName complete path name for the file to be decoded.
499      * @param opts null-ok; Options that control downsampling and whether the
500      *             image should be completely decoded, or just is size returned.
501      * @return The decoded bitmap, or null if the image data could not be
502      *         decoded, or, if opts is non-null, if opts requested only the
503      *         size be returned (in opts.outWidth and opts.outHeight)
504      * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig}
505      *         is {@link android.graphics.Bitmap.Config#HARDWARE}
506      *         and {@link BitmapFactory.Options#inMutable} is set, if the specified color space
507      *         is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer
508      *         function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
509      */
decodeFile(String pathName, Options opts)510     public static Bitmap decodeFile(String pathName, Options opts) {
511         validate(opts);
512         Bitmap bm = null;
513         InputStream stream = null;
514         try {
515             stream = new FileInputStream(pathName);
516             bm = decodeStream(stream, null, opts);
517         } catch (Exception e) {
518             /*  do nothing.
519                 If the exception happened on open, bm will be null.
520             */
521             Log.e("BitmapFactory", "Unable to decode stream: " + e);
522         } finally {
523             if (stream != null) {
524                 try {
525                     stream.close();
526                 } catch (IOException e) {
527                     // do nothing here
528                 }
529             }
530         }
531         return bm;
532     }
533 
534     /**
535      * Decode a file path into a bitmap. If the specified file name is null,
536      * or cannot be decoded into a bitmap, the function returns null.
537      *
538      * @param pathName complete path name for the file to be decoded.
539      * @return the resulting decoded bitmap, or null if it could not be decoded.
540      */
decodeFile(String pathName)541     public static Bitmap decodeFile(String pathName) {
542         return decodeFile(pathName, null);
543     }
544 
545     /**
546      * Decode a new Bitmap from an InputStream. This InputStream was obtained from
547      * resources, which we pass to be able to scale the bitmap accordingly.
548      * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig}
549      *         is {@link android.graphics.Bitmap.Config#HARDWARE}
550      *         and {@link BitmapFactory.Options#inMutable} is set, if the specified color space
551      *         is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer
552      *         function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
553      */
554     @Nullable
decodeResourceStream(@ullable Resources res, @Nullable TypedValue value, @Nullable InputStream is, @Nullable Rect pad, @Nullable Options opts)555     public static Bitmap decodeResourceStream(@Nullable Resources res, @Nullable TypedValue value,
556             @Nullable InputStream is, @Nullable Rect pad, @Nullable Options opts) {
557         validate(opts);
558         if (opts == null) {
559             opts = new Options();
560         }
561 
562         if (opts.inDensity == 0 && value != null) {
563             final int density = value.density;
564             if (density == TypedValue.DENSITY_DEFAULT) {
565                 opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
566             } else if (density != TypedValue.DENSITY_NONE) {
567                 opts.inDensity = density;
568             }
569         }
570 
571         if (opts.inTargetDensity == 0 && res != null) {
572             opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
573         }
574 
575         return decodeStream(is, pad, opts);
576     }
577 
578     /**
579      * Synonym for opening the given resource and calling
580      * {@link #decodeResourceStream}.
581      *
582      * @param res   The resources object containing the image data
583      * @param id The resource id of the image data
584      * @param opts null-ok; Options that control downsampling and whether the
585      *             image should be completely decoded, or just is size returned.
586      * @return The decoded bitmap, or null if the image data could not be
587      *         decoded, or, if opts is non-null, if opts requested only the
588      *         size be returned (in opts.outWidth and opts.outHeight)
589      * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig}
590      *         is {@link android.graphics.Bitmap.Config#HARDWARE}
591      *         and {@link BitmapFactory.Options#inMutable} is set, if the specified color space
592      *         is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer
593      *         function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
594      */
decodeResource(Resources res, int id, Options opts)595     public static Bitmap decodeResource(Resources res, int id, Options opts) {
596         validate(opts);
597         Bitmap bm = null;
598         InputStream is = null;
599 
600         try {
601             final TypedValue value = new TypedValue();
602             is = res.openRawResource(id, value);
603 
604             bm = decodeResourceStream(res, value, is, null, opts);
605         } catch (Exception e) {
606             /*  do nothing.
607                 If the exception happened on open, bm will be null.
608                 If it happened on close, bm is still valid.
609             */
610         } finally {
611             try {
612                 if (is != null) is.close();
613             } catch (IOException e) {
614                 // Ignore
615             }
616         }
617 
618         if (bm == null && opts != null && opts.inBitmap != null) {
619             throw new IllegalArgumentException("Problem decoding into existing bitmap");
620         }
621 
622         return bm;
623     }
624 
625     /**
626      * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}
627      * with null Options.
628      *
629      * @param res The resources object containing the image data
630      * @param id The resource id of the image data
631      * @return The decoded bitmap, or null if the image could not be decoded.
632      */
decodeResource(Resources res, int id)633     public static Bitmap decodeResource(Resources res, int id) {
634         return decodeResource(res, id, null);
635     }
636 
637     /**
638      * Decode an immutable bitmap from the specified byte array.
639      *
640      * @param data byte array of compressed image data
641      * @param offset offset into imageData for where the decoder should begin
642      *               parsing.
643      * @param length the number of bytes, beginning at offset, to parse
644      * @param opts null-ok; Options that control downsampling and whether the
645      *             image should be completely decoded, or just is size returned.
646      * @return The decoded bitmap, or null if the image data could not be
647      *         decoded, or, if opts is non-null, if opts requested only the
648      *         size be returned (in opts.outWidth and opts.outHeight)
649      * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig}
650      *         is {@link android.graphics.Bitmap.Config#HARDWARE}
651      *         and {@link BitmapFactory.Options#inMutable} is set, if the specified color space
652      *         is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer
653      *         function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
654      */
decodeByteArray(byte[] data, int offset, int length, Options opts)655     public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
656         if ((offset | length) < 0 || data.length < offset + length) {
657             throw new ArrayIndexOutOfBoundsException();
658         }
659         validate(opts);
660 
661         Bitmap bm;
662 
663         Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap");
664         try {
665             bm = nativeDecodeByteArray(data, offset, length, opts,
666                     Options.nativeInBitmap(opts),
667                     Options.nativeColorSpace(opts));
668 
669             if (bm == null && opts != null && opts.inBitmap != null) {
670                 throw new IllegalArgumentException("Problem decoding into existing bitmap");
671             }
672             setDensityFromOptions(bm, opts);
673         } finally {
674             Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
675         }
676 
677         return bm;
678     }
679 
680     /**
681      * Decode an immutable bitmap from the specified byte array.
682      *
683      * @param data byte array of compressed image data
684      * @param offset offset into imageData for where the decoder should begin
685      *               parsing.
686      * @param length the number of bytes, beginning at offset, to parse
687      * @return The decoded bitmap, or null if the image could not be decoded.
688      */
decodeByteArray(byte[] data, int offset, int length)689     public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
690         return decodeByteArray(data, offset, length, null);
691     }
692 
693     /**
694      * Set the newly decoded bitmap's density based on the Options.
695      */
setDensityFromOptions(Bitmap outputBitmap, Options opts)696     private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) {
697         if (outputBitmap == null || opts == null) return;
698 
699         final int density = opts.inDensity;
700         if (density != 0) {
701             outputBitmap.setDensity(density);
702             final int targetDensity = opts.inTargetDensity;
703             if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
704                 return;
705             }
706 
707             byte[] np = outputBitmap.getNinePatchChunk();
708             final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
709             if (opts.inScaled || isNinePatch) {
710                 outputBitmap.setDensity(targetDensity);
711             }
712         } else if (opts.inBitmap != null) {
713             // bitmap was reused, ensure density is reset
714             outputBitmap.setDensity(Bitmap.getDefaultDensity());
715         }
716     }
717 
718     /**
719      * Decode an input stream into a bitmap. If the input stream is null, or
720      * cannot be used to decode a bitmap, the function returns null.
721      * The stream's position will be where ever it was after the encoded data
722      * was read.
723      *
724      * @param is The input stream that holds the raw data to be decoded into a
725      *           bitmap.
726      * @param outPadding If not null, return the padding rect for the bitmap if
727      *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
728      *                   no bitmap is returned (null) then padding is
729      *                   unchanged.
730      * @param opts null-ok; Options that control downsampling and whether the
731      *             image should be completely decoded, or just is size returned.
732      * @return The decoded bitmap, or null if the image data could not be
733      *         decoded, or, if opts is non-null, if opts requested only the
734      *         size be returned (in opts.outWidth and opts.outHeight)
735      * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig}
736      *         is {@link android.graphics.Bitmap.Config#HARDWARE}
737      *         and {@link BitmapFactory.Options#inMutable} is set, if the specified color space
738      *         is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer
739      *         function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
740      *
741      * <p class="note">Prior to {@link android.os.Build.VERSION_CODES#KITKAT},
742      * if {@link InputStream#markSupported is.markSupported()} returns true,
743      * <code>is.mark(1024)</code> would be called. As of
744      * {@link android.os.Build.VERSION_CODES#KITKAT}, this is no longer the case.</p>
745      */
746     @Nullable
decodeStream(@ullable InputStream is, @Nullable Rect outPadding, @Nullable Options opts)747     public static Bitmap decodeStream(@Nullable InputStream is, @Nullable Rect outPadding,
748             @Nullable Options opts) {
749         // we don't throw in this case, thus allowing the caller to only check
750         // the cache, and not force the image to be decoded.
751         if (is == null) {
752             return null;
753         }
754         validate(opts);
755 
756         Bitmap bm = null;
757 
758         Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap");
759         try {
760             if (is instanceof AssetManager.AssetInputStream) {
761                 final long asset = ((AssetManager.AssetInputStream) is).getNativeAsset();
762                 bm = nativeDecodeAsset(asset, outPadding, opts, Options.nativeInBitmap(opts),
763                     Options.nativeColorSpace(opts));
764             } else {
765                 bm = decodeStreamInternal(is, outPadding, opts);
766             }
767 
768             if (bm == null && opts != null && opts.inBitmap != null) {
769                 throw new IllegalArgumentException("Problem decoding into existing bitmap");
770             }
771 
772             setDensityFromOptions(bm, opts);
773         } finally {
774             Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
775         }
776 
777         return bm;
778     }
779 
780     /**
781      * Private helper function for decoding an InputStream natively. Buffers the input enough to
782      * do a rewind as needed, and supplies temporary storage if necessary. is MUST NOT be null.
783      */
decodeStreamInternal(@onNull InputStream is, @Nullable Rect outPadding, @Nullable Options opts)784     private static Bitmap decodeStreamInternal(@NonNull InputStream is,
785             @Nullable Rect outPadding, @Nullable Options opts) {
786         // ASSERT(is != null);
787         byte [] tempStorage = null;
788         if (opts != null) tempStorage = opts.inTempStorage;
789         if (tempStorage == null) tempStorage = new byte[DECODE_BUFFER_SIZE];
790         return nativeDecodeStream(is, tempStorage, outPadding, opts,
791                 Options.nativeInBitmap(opts),
792                 Options.nativeColorSpace(opts));
793     }
794 
795     /**
796      * Decode an input stream into a bitmap. If the input stream is null, or
797      * cannot be used to decode a bitmap, the function returns null.
798      * The stream's position will be where ever it was after the encoded data
799      * was read.
800      *
801      * @param is The input stream that holds the raw data to be decoded into a
802      *           bitmap.
803      * @return The decoded bitmap, or null if the image data could not be decoded.
804      */
decodeStream(InputStream is)805     public static Bitmap decodeStream(InputStream is) {
806         return decodeStream(is, null, null);
807     }
808 
809     /**
810      * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
811      * return null. The position within the descriptor will not be changed when
812      * this returns, so the descriptor can be used again as-is.
813      *
814      * @param fd The file descriptor containing the bitmap data to decode
815      * @param outPadding If not null, return the padding rect for the bitmap if
816      *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
817      *                   no bitmap is returned (null) then padding is
818      *                   unchanged.
819      * @param opts null-ok; Options that control downsampling and whether the
820      *             image should be completely decoded, or just its size returned.
821      * @return the decoded bitmap, or null
822      * @throws IllegalArgumentException if {@link BitmapFactory.Options#inPreferredConfig}
823      *         is {@link android.graphics.Bitmap.Config#HARDWARE}
824      *         and {@link BitmapFactory.Options#inMutable} is set, if the specified color space
825      *         is not {@link ColorSpace.Model#RGB RGB}, or if the specified color space's transfer
826      *         function is not an {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}
827      */
decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)828     public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
829         validate(opts);
830         Bitmap bm;
831 
832         Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeFileDescriptor");
833         try {
834             if (nativeIsSeekable(fd)) {
835                 bm = nativeDecodeFileDescriptor(fd, outPadding, opts,
836                         Options.nativeInBitmap(opts),
837                         Options.nativeColorSpace(opts));
838             } else {
839                 FileInputStream fis = new FileInputStream(fd);
840                 try {
841                     bm = decodeStreamInternal(fis, outPadding, opts);
842                 } finally {
843                     try {
844                         fis.close();
845                     } catch (Throwable t) {/* ignore */}
846                 }
847             }
848 
849             if (bm == null && opts != null && opts.inBitmap != null) {
850                 throw new IllegalArgumentException("Problem decoding into existing bitmap");
851             }
852 
853             setDensityFromOptions(bm, opts);
854         } finally {
855             Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
856         }
857         return bm;
858     }
859 
860     /**
861      * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
862      * return null. The position within the descriptor will not be changed when
863      * this returns, so the descriptor can be used again as is.
864      *
865      * @param fd The file descriptor containing the bitmap data to decode
866      * @return the decoded bitmap, or null
867      */
decodeFileDescriptor(FileDescriptor fd)868     public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
869         return decodeFileDescriptor(fd, null, null);
870     }
871 
872     @UnsupportedAppUsage
nativeDecodeStream(InputStream is, byte[] storage, Rect padding, Options opts, long inBitmapHandle, long colorSpaceHandle)873     private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
874             Rect padding, Options opts, long inBitmapHandle, long colorSpaceHandle);
875     @UnsupportedAppUsage
nativeDecodeFileDescriptor(FileDescriptor fd, Rect padding, Options opts, long inBitmapHandle, long colorSpaceHandle)876     private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
877             Rect padding, Options opts, long inBitmapHandle, long colorSpaceHandle);
878     @UnsupportedAppUsage
nativeDecodeAsset(long nativeAsset, Rect padding, Options opts, long inBitmapHandle, long colorSpaceHandle)879     private static native Bitmap nativeDecodeAsset(long nativeAsset, Rect padding, Options opts,
880             long inBitmapHandle, long colorSpaceHandle);
881     @UnsupportedAppUsage
nativeDecodeByteArray(byte[] data, int offset, int length, Options opts, long inBitmapHandle, long colorSpaceHandle)882     private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
883             int length, Options opts, long inBitmapHandle, long colorSpaceHandle);
nativeIsSeekable(FileDescriptor fd)884     private static native boolean nativeIsSeekable(FileDescriptor fd);
885 }
886