1 /*
2  * Copyright (C) 2006 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.annotation.CheckResult;
20 import android.annotation.ColorInt;
21 import android.annotation.ColorLong;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.WorkerThread;
25 import android.compat.annotation.UnsupportedAppUsage;
26 import android.content.res.ResourcesImpl;
27 import android.hardware.HardwareBuffer;
28 import android.os.Build;
29 import android.os.Parcel;
30 import android.os.Parcelable;
31 import android.os.StrictMode;
32 import android.os.Trace;
33 import android.util.DisplayMetrics;
34 import android.util.Half;
35 import android.util.Log;
36 import android.view.ThreadedRenderer;
37 
38 import dalvik.annotation.optimization.CriticalNative;
39 
40 import libcore.util.NativeAllocationRegistry;
41 
42 import java.io.OutputStream;
43 import java.nio.Buffer;
44 import java.nio.ByteBuffer;
45 import java.nio.IntBuffer;
46 import java.nio.ShortBuffer;
47 
48 public final class Bitmap implements Parcelable {
49     private static final String TAG = "Bitmap";
50 
51     /**
52      * Indicates that the bitmap was created for an unknown pixel density.
53      *
54      * @see Bitmap#getDensity()
55      * @see Bitmap#setDensity(int)
56      */
57     public static final int DENSITY_NONE = 0;
58 
59     // Estimated size of the Bitmap native allocation, not including
60     // pixel data.
61     private static final long NATIVE_ALLOCATION_SIZE = 32;
62 
63     // Convenience for JNI access
64     @UnsupportedAppUsage
65     private final long mNativePtr;
66 
67     /**
68      * Represents whether the Bitmap's content is requested to be pre-multiplied.
69      * Note that isPremultiplied() does not directly return this value, because
70      * isPremultiplied() may never return true for a 565 Bitmap or a bitmap
71      * without alpha.
72      *
73      * setPremultiplied() does directly set the value so that setConfig() and
74      * setPremultiplied() aren't order dependent, despite being setters.
75      *
76      * The native bitmap's premultiplication state is kept up to date by
77      * pushing down this preference for every config change.
78      */
79     private boolean mRequestPremultiplied;
80 
81     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769491)
82     private byte[] mNinePatchChunk; // may be null
83     @UnsupportedAppUsage
84     private NinePatch.InsetStruct mNinePatchInsets; // may be null
85     @UnsupportedAppUsage
86     private int mWidth;
87     @UnsupportedAppUsage
88     private int mHeight;
89     private boolean mRecycled;
90 
91     private ColorSpace mColorSpace;
92 
93     /** @hide */
94     public int mDensity = getDefaultDensity();
95 
96     private static volatile int sDefaultDensity = -1;
97 
98     /** @hide Used only when ResourcesImpl.TRACE_FOR_DETAILED_PRELOAD is true. */
99     public static volatile int sPreloadTracingNumInstantiatedBitmaps;
100 
101     /** @hide Used only when ResourcesImpl.TRACE_FOR_DETAILED_PRELOAD is true. */
102     public static volatile long sPreloadTracingTotalBitmapsSize;
103 
104     /**
105      * For backwards compatibility, allows the app layer to change the default
106      * density when running old apps.
107      * @hide
108      */
109     @UnsupportedAppUsage
setDefaultDensity(int density)110     public static void setDefaultDensity(int density) {
111         sDefaultDensity = density;
112     }
113 
114     @SuppressWarnings("deprecation")
115     @UnsupportedAppUsage
getDefaultDensity()116     static int getDefaultDensity() {
117         if (sDefaultDensity >= 0) {
118             return sDefaultDensity;
119         }
120         sDefaultDensity = DisplayMetrics.DENSITY_DEVICE;
121         return sDefaultDensity;
122     }
123 
124     /**
125      * Private constructor that must receive an already allocated native bitmap
126      * int (pointer).
127      */
128     // JNI now calls the version below this one. This is preserved due to UnsupportedAppUsage.
129     @UnsupportedAppUsage(maxTargetSdk = 28)
Bitmap(long nativeBitmap, int width, int height, int density, boolean requestPremultiplied, byte[] ninePatchChunk, NinePatch.InsetStruct ninePatchInsets)130     Bitmap(long nativeBitmap, int width, int height, int density,
131             boolean requestPremultiplied, byte[] ninePatchChunk,
132             NinePatch.InsetStruct ninePatchInsets) {
133         this(nativeBitmap, width, height, density, requestPremultiplied, ninePatchChunk,
134                 ninePatchInsets, true);
135     }
136 
137     // called from JNI and Bitmap_Delegate.
Bitmap(long nativeBitmap, int width, int height, int density, boolean requestPremultiplied, byte[] ninePatchChunk, NinePatch.InsetStruct ninePatchInsets, boolean fromMalloc)138     Bitmap(long nativeBitmap, int width, int height, int density,
139             boolean requestPremultiplied, byte[] ninePatchChunk,
140             NinePatch.InsetStruct ninePatchInsets, boolean fromMalloc) {
141         if (nativeBitmap == 0) {
142             throw new RuntimeException("internal error: native bitmap is 0");
143         }
144 
145         mWidth = width;
146         mHeight = height;
147         mRequestPremultiplied = requestPremultiplied;
148 
149         mNinePatchChunk = ninePatchChunk;
150         mNinePatchInsets = ninePatchInsets;
151         if (density >= 0) {
152             mDensity = density;
153         }
154 
155         mNativePtr = nativeBitmap;
156 
157         final int allocationByteCount = getAllocationByteCount();
158         NativeAllocationRegistry registry;
159         if (fromMalloc) {
160             registry = NativeAllocationRegistry.createMalloced(
161                     Bitmap.class.getClassLoader(), nativeGetNativeFinalizer(), allocationByteCount);
162         } else {
163             registry = NativeAllocationRegistry.createNonmalloced(
164                     Bitmap.class.getClassLoader(), nativeGetNativeFinalizer(), allocationByteCount);
165         }
166         registry.registerNativeAllocation(this, nativeBitmap);
167 
168         if (ResourcesImpl.TRACE_FOR_DETAILED_PRELOAD) {
169             sPreloadTracingNumInstantiatedBitmaps++;
170             long nativeSize = NATIVE_ALLOCATION_SIZE + allocationByteCount;
171             sPreloadTracingTotalBitmapsSize += nativeSize;
172         }
173     }
174 
175     /**
176      * Return the pointer to the native object.
177      * @hide
178      */
getNativeInstance()179     public long getNativeInstance() {
180         return mNativePtr;
181     }
182 
183     /**
184      * Native bitmap has been reconfigured, so set premult and cached
185      * width/height values
186      */
187     @SuppressWarnings("unused") // called from JNI
188     @UnsupportedAppUsage
reinit(int width, int height, boolean requestPremultiplied)189     void reinit(int width, int height, boolean requestPremultiplied) {
190         mWidth = width;
191         mHeight = height;
192         mRequestPremultiplied = requestPremultiplied;
193         mColorSpace = null;
194     }
195 
196     /**
197      * <p>Returns the density for this bitmap.</p>
198      *
199      * <p>The default density is the same density as the current display,
200      * unless the current application does not support different screen
201      * densities in which case it is
202      * {@link android.util.DisplayMetrics#DENSITY_DEFAULT}.  Note that
203      * compatibility mode is determined by the application that was initially
204      * loaded into a process -- applications that share the same process should
205      * all have the same compatibility, or ensure they explicitly set the
206      * density of their bitmaps appropriately.</p>
207      *
208      * @return A scaling factor of the default density or {@link #DENSITY_NONE}
209      *         if the scaling factor is unknown.
210      *
211      * @see #setDensity(int)
212      * @see android.util.DisplayMetrics#DENSITY_DEFAULT
213      * @see android.util.DisplayMetrics#densityDpi
214      * @see #DENSITY_NONE
215      */
getDensity()216     public int getDensity() {
217         if (mRecycled) {
218             Log.w(TAG, "Called getDensity() on a recycle()'d bitmap! This is undefined behavior!");
219         }
220         return mDensity;
221     }
222 
223     /**
224      * <p>Specifies the density for this bitmap.  When the bitmap is
225      * drawn to a Canvas that also has a density, it will be scaled
226      * appropriately.</p>
227      *
228      * @param density The density scaling factor to use with this bitmap or
229      *        {@link #DENSITY_NONE} if the density is unknown.
230      *
231      * @see #getDensity()
232      * @see android.util.DisplayMetrics#DENSITY_DEFAULT
233      * @see android.util.DisplayMetrics#densityDpi
234      * @see #DENSITY_NONE
235      */
setDensity(int density)236     public void setDensity(int density) {
237         mDensity = density;
238     }
239 
240     /**
241      * <p>Modifies the bitmap to have a specified width, height, and {@link
242      * Config}, without affecting the underlying allocation backing the bitmap.
243      * Bitmap pixel data is not re-initialized for the new configuration.</p>
244      *
245      * <p>This method can be used to avoid allocating a new bitmap, instead
246      * reusing an existing bitmap's allocation for a new configuration of equal
247      * or lesser size. If the Bitmap's allocation isn't large enough to support
248      * the new configuration, an IllegalArgumentException will be thrown and the
249      * bitmap will not be modified.</p>
250      *
251      * <p>The result of {@link #getByteCount()} will reflect the new configuration,
252      * while {@link #getAllocationByteCount()} will reflect that of the initial
253      * configuration.</p>
254      *
255      * <p>Note: This may change this result of hasAlpha(). When converting to 565,
256      * the new bitmap will always be considered opaque. When converting from 565,
257      * the new bitmap will be considered non-opaque, and will respect the value
258      * set by setPremultiplied().</p>
259      *
260      * <p>WARNING: This method should NOT be called on a bitmap currently in use
261      * by the view system, Canvas, or the AndroidBitmap NDK API. It does not
262      * make guarantees about how the underlying pixel buffer is remapped to the
263      * new config, just that the allocation is reused. Additionally, the view
264      * system does not account for bitmap properties being modifying during use,
265      * e.g. while attached to drawables.</p>
266      *
267      * <p>In order to safely ensure that a Bitmap is no longer in use by the
268      * View system it is necessary to wait for a draw pass to occur after
269      * invalidate()'ing any view that had previously drawn the Bitmap in the last
270      * draw pass due to hardware acceleration's caching of draw commands. As
271      * an example, here is how this can be done for an ImageView:
272      * <pre class="prettyprint">
273      *      ImageView myImageView = ...;
274      *      final Bitmap myBitmap = ...;
275      *      myImageView.setImageDrawable(null);
276      *      myImageView.post(new Runnable() {
277      *          public void run() {
278      *              // myBitmap is now no longer in use by the ImageView
279      *              // and can be safely reconfigured.
280      *              myBitmap.reconfigure(...);
281      *          }
282      *      });
283      * </pre></p>
284      *
285      * @see #setWidth(int)
286      * @see #setHeight(int)
287      * @see #setConfig(Config)
288      */
reconfigure(int width, int height, Config config)289     public void reconfigure(int width, int height, Config config) {
290         checkRecycled("Can't call reconfigure() on a recycled bitmap");
291         if (width <= 0 || height <= 0) {
292             throw new IllegalArgumentException("width and height must be > 0");
293         }
294         if (!isMutable()) {
295             throw new IllegalStateException("only mutable bitmaps may be reconfigured");
296         }
297 
298         nativeReconfigure(mNativePtr, width, height, config.nativeInt, mRequestPremultiplied);
299         mWidth = width;
300         mHeight = height;
301         mColorSpace = null;
302     }
303 
304     /**
305      * <p>Convenience method for calling {@link #reconfigure(int, int, Config)}
306      * with the current height and config.</p>
307      *
308      * <p>WARNING: this method should not be used on bitmaps currently used by
309      * the view system, see {@link #reconfigure(int, int, Config)} for more
310      * details.</p>
311      *
312      * @see #reconfigure(int, int, Config)
313      * @see #setHeight(int)
314      * @see #setConfig(Config)
315      */
setWidth(int width)316     public void setWidth(int width) {
317         reconfigure(width, getHeight(), getConfig());
318     }
319 
320     /**
321      * <p>Convenience method for calling {@link #reconfigure(int, int, Config)}
322      * with the current width and config.</p>
323      *
324      * <p>WARNING: this method should not be used on bitmaps currently used by
325      * the view system, see {@link #reconfigure(int, int, Config)} for more
326      * details.</p>
327      *
328      * @see #reconfigure(int, int, Config)
329      * @see #setWidth(int)
330      * @see #setConfig(Config)
331      */
setHeight(int height)332     public void setHeight(int height) {
333         reconfigure(getWidth(), height, getConfig());
334     }
335 
336     /**
337      * <p>Convenience method for calling {@link #reconfigure(int, int, Config)}
338      * with the current height and width.</p>
339      *
340      * <p>WARNING: this method should not be used on bitmaps currently used by
341      * the view system, see {@link #reconfigure(int, int, Config)} for more
342      * details.</p>
343      *
344      * @see #reconfigure(int, int, Config)
345      * @see #setWidth(int)
346      * @see #setHeight(int)
347      */
setConfig(Config config)348     public void setConfig(Config config) {
349         reconfigure(getWidth(), getHeight(), config);
350     }
351 
352     /**
353      * Sets the nine patch chunk.
354      *
355      * @param chunk The definition of the nine patch
356      *
357      * @hide
358      */
359     @UnsupportedAppUsage
setNinePatchChunk(byte[] chunk)360     public void setNinePatchChunk(byte[] chunk) {
361         mNinePatchChunk = chunk;
362     }
363 
364     /**
365      * Free the native object associated with this bitmap, and clear the
366      * reference to the pixel data. This will not free the pixel data synchronously;
367      * it simply allows it to be garbage collected if there are no other references.
368      * The bitmap is marked as "dead", meaning it will throw an exception if
369      * getPixels() or setPixels() is called, and will draw nothing. This operation
370      * cannot be reversed, so it should only be called if you are sure there are no
371      * further uses for the bitmap. This is an advanced call, and normally need
372      * not be called, since the normal GC process will free up this memory when
373      * there are no more references to this bitmap.
374      */
recycle()375     public void recycle() {
376         if (!mRecycled) {
377             nativeRecycle(mNativePtr);
378             mNinePatchChunk = null;
379             mRecycled = true;
380         }
381     }
382 
383     /**
384      * Returns true if this bitmap has been recycled. If so, then it is an error
385      * to try to access its pixels, and the bitmap will not draw.
386      *
387      * @return true if the bitmap has been recycled
388      */
isRecycled()389     public final boolean isRecycled() {
390         return mRecycled;
391     }
392 
393     /**
394      * Returns the generation ID of this bitmap. The generation ID changes
395      * whenever the bitmap is modified. This can be used as an efficient way to
396      * check if a bitmap has changed.
397      *
398      * @return The current generation ID for this bitmap.
399      */
getGenerationId()400     public int getGenerationId() {
401         if (mRecycled) {
402             Log.w(TAG, "Called getGenerationId() on a recycle()'d bitmap! This is undefined behavior!");
403         }
404         return nativeGenerationId(mNativePtr);
405     }
406 
407     /**
408      * This is called by methods that want to throw an exception if the bitmap
409      * has already been recycled.
410      */
checkRecycled(String errorMessage)411     private void checkRecycled(String errorMessage) {
412         if (mRecycled) {
413             throw new IllegalStateException(errorMessage);
414         }
415     }
416 
417     /**
418      * This is called by methods that want to throw an exception if the bitmap
419      * is {@link Config#HARDWARE}.
420      */
checkHardware(String errorMessage)421     private void checkHardware(String errorMessage) {
422         if (getConfig() == Config.HARDWARE) {
423             throw new IllegalStateException(errorMessage);
424         }
425     }
426 
427     /**
428      * Common code for checking that x and y are >= 0
429      *
430      * @param x x coordinate to ensure is >= 0
431      * @param y y coordinate to ensure is >= 0
432      */
checkXYSign(int x, int y)433     private static void checkXYSign(int x, int y) {
434         if (x < 0) {
435             throw new IllegalArgumentException("x must be >= 0");
436         }
437         if (y < 0) {
438             throw new IllegalArgumentException("y must be >= 0");
439         }
440     }
441 
442     /**
443      * Common code for checking that width and height are > 0
444      *
445      * @param width  width to ensure is > 0
446      * @param height height to ensure is > 0
447      */
checkWidthHeight(int width, int height)448     private static void checkWidthHeight(int width, int height) {
449         if (width <= 0) {
450             throw new IllegalArgumentException("width must be > 0");
451         }
452         if (height <= 0) {
453             throw new IllegalArgumentException("height must be > 0");
454         }
455     }
456 
457     /**
458      * Possible bitmap configurations. A bitmap configuration describes
459      * how pixels are stored. This affects the quality (color depth) as
460      * well as the ability to display transparent/translucent colors.
461      */
462     public enum Config {
463         // these native values must match up with the enum in SkBitmap.h
464 
465         /**
466          * Each pixel is stored as a single translucency (alpha) channel.
467          * This is very useful to efficiently store masks for instance.
468          * No color information is stored.
469          * With this configuration, each pixel requires 1 byte of memory.
470          */
471         ALPHA_8     (1),
472 
473         /**
474          * Each pixel is stored on 2 bytes and only the RGB channels are
475          * encoded: red is stored with 5 bits of precision (32 possible
476          * values), green is stored with 6 bits of precision (64 possible
477          * values) and blue is stored with 5 bits of precision.
478          *
479          * This configuration can produce slight visual artifacts depending
480          * on the configuration of the source. For instance, without
481          * dithering, the result might show a greenish tint. To get better
482          * results dithering should be applied.
483          *
484          * This configuration may be useful when using opaque bitmaps
485          * that do not require high color fidelity.
486          *
487          * <p>Use this formula to pack into 16 bits:</p>
488          * <pre class="prettyprint">
489          * short color = (R & 0x1f) << 11 | (G & 0x3f) << 5 | (B & 0x1f);
490          * </pre>
491          */
492         RGB_565     (3),
493 
494         /**
495          * Each pixel is stored on 2 bytes. The three RGB color channels
496          * and the alpha channel (translucency) are stored with a 4 bits
497          * precision (16 possible values.)
498          *
499          * This configuration is mostly useful if the application needs
500          * to store translucency information but also needs to save
501          * memory.
502          *
503          * It is recommended to use {@link #ARGB_8888} instead of this
504          * configuration.
505          *
506          * Note: as of {@link android.os.Build.VERSION_CODES#KITKAT},
507          * any bitmap created with this configuration will be created
508          * using {@link #ARGB_8888} instead.
509          *
510          * @deprecated Because of the poor quality of this configuration,
511          *             it is advised to use {@link #ARGB_8888} instead.
512          */
513         @Deprecated
514         ARGB_4444   (4),
515 
516         /**
517          * Each pixel is stored on 4 bytes. Each channel (RGB and alpha
518          * for translucency) is stored with 8 bits of precision (256
519          * possible values.)
520          *
521          * This configuration is very flexible and offers the best
522          * quality. It should be used whenever possible.
523          *
524          * <p>Use this formula to pack into 32 bits:</p>
525          * <pre class="prettyprint">
526          * int color = (A & 0xff) << 24 | (B & 0xff) << 16 | (G & 0xff) << 8 | (R & 0xff);
527          * </pre>
528          */
529         ARGB_8888   (5),
530 
531         /**
532          * Each pixels is stored on 8 bytes. Each channel (RGB and alpha
533          * for translucency) is stored as a
534          * {@link android.util.Half half-precision floating point value}.
535          *
536          * This configuration is particularly suited for wide-gamut and
537          * HDR content.
538          *
539          * <p>Use this formula to pack into 64 bits:</p>
540          * <pre class="prettyprint">
541          * long color = (A & 0xffff) << 48 | (B & 0xffff) << 32 | (G & 0xffff) << 16 | (R & 0xffff);
542          * </pre>
543          */
544         RGBA_F16    (6),
545 
546         /**
547          * Special configuration, when bitmap is stored only in graphic memory.
548          * Bitmaps in this configuration are always immutable.
549          *
550          * It is optimal for cases, when the only operation with the bitmap is to draw it on a
551          * screen.
552          */
553         HARDWARE    (7);
554 
555         @UnsupportedAppUsage
556         final int nativeInt;
557 
558         private static Config sConfigs[] = {
559             null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888, RGBA_F16, HARDWARE
560         };
561 
Config(int ni)562         Config(int ni) {
563             this.nativeInt = ni;
564         }
565 
566         @UnsupportedAppUsage
nativeToConfig(int ni)567         static Config nativeToConfig(int ni) {
568             return sConfigs[ni];
569         }
570     }
571 
572     /**
573      * <p>Copy the bitmap's pixels into the specified buffer (allocated by the
574      * caller). An exception is thrown if the buffer is not large enough to
575      * hold all of the pixels (taking into account the number of bytes per
576      * pixel) or if the Buffer subclass is not one of the support types
577      * (ByteBuffer, ShortBuffer, IntBuffer).</p>
578      * <p>The content of the bitmap is copied into the buffer as-is. This means
579      * that if this bitmap stores its pixels pre-multiplied
580      * (see {@link #isPremultiplied()}, the values in the buffer will also be
581      * pre-multiplied. The pixels remain in the color space of the bitmap.</p>
582      * <p>After this method returns, the current position of the buffer is
583      * updated: the position is incremented by the number of elements written
584      * in the buffer.</p>
585      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
586      */
copyPixelsToBuffer(Buffer dst)587     public void copyPixelsToBuffer(Buffer dst) {
588         checkHardware("unable to copyPixelsToBuffer, "
589                 + "pixel access is not supported on Config#HARDWARE bitmaps");
590         int elements = dst.remaining();
591         int shift;
592         if (dst instanceof ByteBuffer) {
593             shift = 0;
594         } else if (dst instanceof ShortBuffer) {
595             shift = 1;
596         } else if (dst instanceof IntBuffer) {
597             shift = 2;
598         } else {
599             throw new RuntimeException("unsupported Buffer subclass");
600         }
601 
602         long bufferSize = (long)elements << shift;
603         long pixelSize = getByteCount();
604 
605         if (bufferSize < pixelSize) {
606             throw new RuntimeException("Buffer not large enough for pixels");
607         }
608 
609         nativeCopyPixelsToBuffer(mNativePtr, dst);
610 
611         // now update the buffer's position
612         int position = dst.position();
613         position += pixelSize >> shift;
614         dst.position(position);
615     }
616 
617     /**
618      * <p>Copy the pixels from the buffer, beginning at the current position,
619      * overwriting the bitmap's pixels. The data in the buffer is not changed
620      * in any way (unlike setPixels(), which converts from unpremultipled 32bit
621      * to whatever the bitmap's native format is. The pixels in the source
622      * buffer are assumed to be in the bitmap's color space.</p>
623      * <p>After this method returns, the current position of the buffer is
624      * updated: the position is incremented by the number of elements read from
625      * the buffer. If you need to read the bitmap from the buffer again you must
626      * first rewind the buffer.</p>
627      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
628      */
copyPixelsFromBuffer(Buffer src)629     public void copyPixelsFromBuffer(Buffer src) {
630         checkRecycled("copyPixelsFromBuffer called on recycled bitmap");
631         checkHardware("unable to copyPixelsFromBuffer, Config#HARDWARE bitmaps are immutable");
632 
633         int elements = src.remaining();
634         int shift;
635         if (src instanceof ByteBuffer) {
636             shift = 0;
637         } else if (src instanceof ShortBuffer) {
638             shift = 1;
639         } else if (src instanceof IntBuffer) {
640             shift = 2;
641         } else {
642             throw new RuntimeException("unsupported Buffer subclass");
643         }
644 
645         long bufferBytes = (long) elements << shift;
646         long bitmapBytes = getByteCount();
647 
648         if (bufferBytes < bitmapBytes) {
649             throw new RuntimeException("Buffer not large enough for pixels");
650         }
651 
652         nativeCopyPixelsFromBuffer(mNativePtr, src);
653 
654         // now update the buffer's position
655         int position = src.position();
656         position += bitmapBytes >> shift;
657         src.position(position);
658     }
659 
noteHardwareBitmapSlowCall()660     private void noteHardwareBitmapSlowCall() {
661         if (getConfig() == Config.HARDWARE) {
662             StrictMode.noteSlowCall("Warning: attempt to read pixels from hardware "
663                     + "bitmap, which is very slow operation");
664         }
665     }
666 
667     /**
668      * Tries to make a new bitmap based on the dimensions of this bitmap,
669      * setting the new bitmap's config to the one specified, and then copying
670      * this bitmap's pixels into the new bitmap. If the conversion is not
671      * supported, or the allocator fails, then this returns NULL.  The returned
672      * bitmap has the same density and color space as the original, except in
673      * the following cases. When copying to {@link Config#ALPHA_8}, the color
674      * space is dropped. When copying to or from {@link Config#RGBA_F16},
675      * EXTENDED or non-EXTENDED variants may be adjusted as appropriate.
676      *
677      * @param config    The desired config for the resulting bitmap
678      * @param isMutable True if the resulting bitmap should be mutable (i.e.
679      *                  its pixels can be modified)
680      * @return the new bitmap, or null if the copy could not be made.
681      * @throws IllegalArgumentException if config is {@link Config#HARDWARE} and isMutable is true
682      */
copy(Config config, boolean isMutable)683     public Bitmap copy(Config config, boolean isMutable) {
684         checkRecycled("Can't copy a recycled bitmap");
685         if (config == Config.HARDWARE && isMutable) {
686             throw new IllegalArgumentException("Hardware bitmaps are always immutable");
687         }
688         noteHardwareBitmapSlowCall();
689         Bitmap b = nativeCopy(mNativePtr, config.nativeInt, isMutable);
690         if (b != null) {
691             b.setPremultiplied(mRequestPremultiplied);
692             b.mDensity = mDensity;
693         }
694         return b;
695     }
696 
697     /**
698      * Creates a new immutable bitmap backed by ashmem which can efficiently
699      * be passed between processes. The bitmap is assumed to be in the sRGB
700      * color space.
701      *
702      * @hide
703      */
704     @UnsupportedAppUsage
createAshmemBitmap()705     public Bitmap createAshmemBitmap() {
706         checkRecycled("Can't copy a recycled bitmap");
707         noteHardwareBitmapSlowCall();
708         Bitmap b = nativeCopyAshmem(mNativePtr);
709         if (b != null) {
710             b.setPremultiplied(mRequestPremultiplied);
711             b.mDensity = mDensity;
712         }
713         return b;
714     }
715 
716     /**
717      * Creates a new immutable bitmap backed by ashmem which can efficiently
718      * be passed between processes. The bitmap is assumed to be in the sRGB
719      * color space.
720      *
721      * @hide
722      */
723     @UnsupportedAppUsage
createAshmemBitmap(Config config)724     public Bitmap createAshmemBitmap(Config config) {
725         checkRecycled("Can't copy a recycled bitmap");
726         noteHardwareBitmapSlowCall();
727         Bitmap b = nativeCopyAshmemConfig(mNativePtr, config.nativeInt);
728         if (b != null) {
729             b.setPremultiplied(mRequestPremultiplied);
730             b.mDensity = mDensity;
731         }
732         return b;
733     }
734 
735     /**
736      * Create a hardware bitmap backed by a {@link HardwareBuffer}.
737      *
738      * <p>The passed HardwareBuffer's usage flags must contain
739      * {@link HardwareBuffer#USAGE_GPU_SAMPLED_IMAGE}.
740      *
741      * <p>The bitmap will keep a reference to the buffer so that callers can safely close the
742      * HardwareBuffer without affecting the Bitmap. However the HardwareBuffer must not be
743      * modified while a wrapped Bitmap is accessing it. Doing so will result in undefined behavior.
744      *
745      * @param hardwareBuffer The HardwareBuffer to wrap.
746      * @param colorSpace The color space of the bitmap. Must be a {@link ColorSpace.Rgb} colorspace.
747      *                   If null, SRGB is assumed.
748      * @return A bitmap wrapping the buffer, or null if there was a problem creating the bitmap.
749      * @throws IllegalArgumentException if the HardwareBuffer has an invalid usage, or an invalid
750      *                                  colorspace is given.
751      */
752     @Nullable
wrapHardwareBuffer(@onNull HardwareBuffer hardwareBuffer, @Nullable ColorSpace colorSpace)753     public static Bitmap wrapHardwareBuffer(@NonNull HardwareBuffer hardwareBuffer,
754             @Nullable ColorSpace colorSpace) {
755         if ((hardwareBuffer.getUsage() & HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE) == 0) {
756             throw new IllegalArgumentException("usage flags must contain USAGE_GPU_SAMPLED_IMAGE.");
757         }
758         int format = hardwareBuffer.getFormat();
759         if (colorSpace == null) {
760             colorSpace = ColorSpace.get(ColorSpace.Named.SRGB);
761         }
762         return nativeWrapHardwareBufferBitmap(hardwareBuffer, colorSpace.getNativeInstance());
763     }
764 
765     /**
766      * Utility method to create a hardware backed bitmap using the graphics buffer.
767      * @hide
768      */
769     @Nullable
wrapHardwareBuffer(@onNull GraphicBuffer graphicBuffer, @Nullable ColorSpace colorSpace)770     public static Bitmap wrapHardwareBuffer(@NonNull GraphicBuffer graphicBuffer,
771             @Nullable ColorSpace colorSpace) {
772         try (HardwareBuffer hb = HardwareBuffer.createFromGraphicBuffer(graphicBuffer)) {
773             return wrapHardwareBuffer(hb, colorSpace);
774         }
775     }
776 
777     /**
778      * Creates a new bitmap, scaled from an existing bitmap, when possible. If the
779      * specified width and height are the same as the current width and height of
780      * the source bitmap, the source bitmap is returned and no new bitmap is
781      * created.
782      *
783      * @param src       The source bitmap.
784      * @param dstWidth  The new bitmap's desired width.
785      * @param dstHeight The new bitmap's desired height.
786      * @param filter    Whether or not bilinear filtering should be used when scaling the
787      *                  bitmap. If this is true then bilinear filtering will be used when
788      *                  scaling which has better image quality at the cost of worse performance.
789      *                  If this is false then nearest-neighbor scaling is used instead which
790      *                  will have worse image quality but is faster. Recommended default
791      *                  is to set filter to 'true' as the cost of bilinear filtering is
792      *                  typically minimal and the improved image quality is significant.
793      * @return The new scaled bitmap or the source bitmap if no scaling is required.
794      * @throws IllegalArgumentException if width is <= 0, or height is <= 0
795      */
createScaledBitmap(@onNull Bitmap src, int dstWidth, int dstHeight, boolean filter)796     public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight,
797             boolean filter) {
798         Matrix m = new Matrix();
799 
800         final int width = src.getWidth();
801         final int height = src.getHeight();
802         if (width != dstWidth || height != dstHeight) {
803             final float sx = dstWidth / (float) width;
804             final float sy = dstHeight / (float) height;
805             m.setScale(sx, sy);
806         }
807         return Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
808     }
809 
810     /**
811      * Returns a bitmap from the source bitmap. The new bitmap may
812      * be the same object as source, or a copy may have been made.  It is
813      * initialized with the same density and color space as the original bitmap.
814      */
createBitmap(@onNull Bitmap src)815     public static Bitmap createBitmap(@NonNull Bitmap src) {
816         return createBitmap(src, 0, 0, src.getWidth(), src.getHeight());
817     }
818 
819     /**
820      * Returns a bitmap from the specified subset of the source
821      * bitmap. The new bitmap may be the same object as source, or a copy may
822      * have been made. It is initialized with the same density and color space
823      * as the original bitmap.
824      *
825      * @param source   The bitmap we are subsetting
826      * @param x        The x coordinate of the first pixel in source
827      * @param y        The y coordinate of the first pixel in source
828      * @param width    The number of pixels in each row
829      * @param height   The number of rows
830      * @return A copy of a subset of the source bitmap or the source bitmap itself.
831      * @throws IllegalArgumentException if the x, y, width, height values are
832      *         outside of the dimensions of the source bitmap, or width is <= 0,
833      *         or height is <= 0
834      */
createBitmap(@onNull Bitmap source, int x, int y, int width, int height)835     public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height) {
836         return createBitmap(source, x, y, width, height, null, false);
837     }
838 
839     /**
840      * Returns a bitmap from subset of the source bitmap,
841      * transformed by the optional matrix. The new bitmap may be the
842      * same object as source, or a copy may have been made. It is
843      * initialized with the same density and color space as the original
844      * bitmap.
845      *
846      * If the source bitmap is immutable and the requested subset is the
847      * same as the source bitmap itself, then the source bitmap is
848      * returned and no new bitmap is created.
849      *
850      * The returned bitmap will always be mutable except in the following scenarios:
851      * (1) In situations where the source bitmap is returned and the source bitmap is immutable
852      *
853      * (2) The source bitmap is a hardware bitmap. That is {@link #getConfig()} is equivalent to
854      * {@link Config#HARDWARE}
855      *
856      * @param source   The bitmap we are subsetting
857      * @param x        The x coordinate of the first pixel in source
858      * @param y        The y coordinate of the first pixel in source
859      * @param width    The number of pixels in each row
860      * @param height   The number of rows
861      * @param m        Optional matrix to be applied to the pixels
862      * @param filter   true if the source should be filtered.
863      *                   Only applies if the matrix contains more than just
864      *                   translation.
865      * @return A bitmap that represents the specified subset of source
866      * @throws IllegalArgumentException if the x, y, width, height values are
867      *         outside of the dimensions of the source bitmap, or width is <= 0,
868      *         or height is <= 0, or if the source bitmap has already been recycled
869      */
createBitmap(@onNull Bitmap source, int x, int y, int width, int height, @Nullable Matrix m, boolean filter)870     public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height,
871             @Nullable Matrix m, boolean filter) {
872 
873         checkXYSign(x, y);
874         checkWidthHeight(width, height);
875         if (x + width > source.getWidth()) {
876             throw new IllegalArgumentException("x + width must be <= bitmap.width()");
877         }
878         if (y + height > source.getHeight()) {
879             throw new IllegalArgumentException("y + height must be <= bitmap.height()");
880         }
881         if (source.isRecycled()) {
882             throw new IllegalArgumentException("cannot use a recycled source in createBitmap");
883         }
884 
885         // check if we can just return our argument unchanged
886         if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
887                 height == source.getHeight() && (m == null || m.isIdentity())) {
888             return source;
889         }
890 
891         boolean isHardware = source.getConfig() == Config.HARDWARE;
892         if (isHardware) {
893             source.noteHardwareBitmapSlowCall();
894             source = nativeCopyPreserveInternalConfig(source.mNativePtr);
895         }
896 
897         int neww = width;
898         int newh = height;
899         Bitmap bitmap;
900         Paint paint;
901 
902         Rect srcR = new Rect(x, y, x + width, y + height);
903         RectF dstR = new RectF(0, 0, width, height);
904         RectF deviceR = new RectF();
905 
906         Config newConfig = Config.ARGB_8888;
907         final Config config = source.getConfig();
908         // GIF files generate null configs, assume ARGB_8888
909         if (config != null) {
910             switch (config) {
911                 case RGB_565:
912                     newConfig = Config.RGB_565;
913                     break;
914                 case ALPHA_8:
915                     newConfig = Config.ALPHA_8;
916                     break;
917                 case RGBA_F16:
918                     newConfig = Config.RGBA_F16;
919                     break;
920                 //noinspection deprecation
921                 case ARGB_4444:
922                 case ARGB_8888:
923                 default:
924                     newConfig = Config.ARGB_8888;
925                     break;
926             }
927         }
928 
929         ColorSpace cs = source.getColorSpace();
930 
931         if (m == null || m.isIdentity()) {
932             bitmap = createBitmap(null, neww, newh, newConfig, source.hasAlpha(), cs);
933             paint = null;   // not needed
934         } else {
935             final boolean transformed = !m.rectStaysRect();
936 
937             m.mapRect(deviceR, dstR);
938 
939             neww = Math.round(deviceR.width());
940             newh = Math.round(deviceR.height());
941 
942             Config transformedConfig = newConfig;
943             if (transformed) {
944                 if (transformedConfig != Config.ARGB_8888 && transformedConfig != Config.RGBA_F16) {
945                     transformedConfig = Config.ARGB_8888;
946                     if (cs == null) {
947                         cs = ColorSpace.get(ColorSpace.Named.SRGB);
948                     }
949                 }
950             }
951 
952             bitmap = createBitmap(null, neww, newh, transformedConfig,
953                     transformed || source.hasAlpha(), cs);
954 
955             paint = new Paint();
956             paint.setFilterBitmap(filter);
957             if (transformed) {
958                 paint.setAntiAlias(true);
959             }
960         }
961 
962         // The new bitmap was created from a known bitmap source so assume that
963         // they use the same density
964         bitmap.mDensity = source.mDensity;
965         bitmap.setHasAlpha(source.hasAlpha());
966         bitmap.setPremultiplied(source.mRequestPremultiplied);
967 
968         Canvas canvas = new Canvas(bitmap);
969         canvas.translate(-deviceR.left, -deviceR.top);
970         canvas.concat(m);
971         canvas.drawBitmap(source, srcR, dstR, paint);
972         canvas.setBitmap(null);
973         if (isHardware) {
974             return bitmap.copy(Config.HARDWARE, false);
975         }
976         return bitmap;
977     }
978 
979     /**
980      * Returns a mutable bitmap with the specified width and height.  Its
981      * initial density is as per {@link #getDensity}. The newly created
982      * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
983      *
984      * @param width    The width of the bitmap
985      * @param height   The height of the bitmap
986      * @param config   The bitmap config to create.
987      * @throws IllegalArgumentException if the width or height are <= 0, or if
988      *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
989      */
createBitmap(int width, int height, @NonNull Config config)990     public static Bitmap createBitmap(int width, int height, @NonNull Config config) {
991         return createBitmap(width, height, config, true);
992     }
993 
994     /**
995      * Returns a mutable bitmap with the specified width and height.  Its
996      * initial density is determined from the given {@link DisplayMetrics}.
997      * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
998      * color space.
999      *
1000      * @param display  Display metrics for the display this bitmap will be
1001      *                 drawn on.
1002      * @param width    The width of the bitmap
1003      * @param height   The height of the bitmap
1004      * @param config   The bitmap config to create.
1005      * @throws IllegalArgumentException if the width or height are <= 0, or if
1006      *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
1007      */
createBitmap(@ullable DisplayMetrics display, int width, int height, @NonNull Config config)1008     public static Bitmap createBitmap(@Nullable DisplayMetrics display, int width,
1009             int height, @NonNull Config config) {
1010         return createBitmap(display, width, height, config, true);
1011     }
1012 
1013     /**
1014      * Returns a mutable bitmap with the specified width and height.  Its
1015      * initial density is as per {@link #getDensity}. The newly created
1016      * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
1017      *
1018      * @param width    The width of the bitmap
1019      * @param height   The height of the bitmap
1020      * @param config   The bitmap config to create.
1021      * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
1022      *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
1023      *                 instead of transparent.
1024      *
1025      * @throws IllegalArgumentException if the width or height are <= 0, or if
1026      *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
1027      */
createBitmap(int width, int height, @NonNull Config config, boolean hasAlpha)1028     public static Bitmap createBitmap(int width, int height,
1029             @NonNull Config config, boolean hasAlpha) {
1030         return createBitmap(null, width, height, config, hasAlpha);
1031     }
1032 
1033     /**
1034      * Returns a mutable bitmap with the specified width and height.  Its
1035      * initial density is as per {@link #getDensity}.
1036      *
1037      * @param width    The width of the bitmap
1038      * @param height   The height of the bitmap
1039      * @param config   The bitmap config to create.
1040      * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
1041      *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
1042      *                 instead of transparent.
1043      * @param colorSpace The color space of the bitmap. If the config is {@link Config#RGBA_F16}
1044      *                   and {@link ColorSpace.Named#SRGB sRGB} or
1045      *                   {@link ColorSpace.Named#LINEAR_SRGB Linear sRGB} is provided then the
1046      *                   corresponding extended range variant is assumed.
1047      *
1048      * @throws IllegalArgumentException if the width or height are <= 0, if
1049      *         Config is Config.HARDWARE (because hardware bitmaps are always
1050      *         immutable), if the specified color space is not {@link ColorSpace.Model#RGB RGB},
1051      *         if the specified color space's transfer function is not an
1052      *         {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}, or if
1053      *         the color space is null
1054      */
createBitmap(int width, int height, @NonNull Config config, boolean hasAlpha, @NonNull ColorSpace colorSpace)1055     public static Bitmap createBitmap(int width, int height, @NonNull Config config,
1056             boolean hasAlpha, @NonNull ColorSpace colorSpace) {
1057         return createBitmap(null, width, height, config, hasAlpha, colorSpace);
1058     }
1059 
1060     /**
1061      * Returns a mutable bitmap with the specified width and height.  Its
1062      * initial density is determined from the given {@link DisplayMetrics}.
1063      * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
1064      * color space.
1065      *
1066      * @param display  Display metrics for the display this bitmap will be
1067      *                 drawn on.
1068      * @param width    The width of the bitmap
1069      * @param height   The height of the bitmap
1070      * @param config   The bitmap config to create.
1071      * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
1072      *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
1073      *                 instead of transparent.
1074      *
1075      * @throws IllegalArgumentException if the width or height are <= 0, or if
1076      *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
1077      */
createBitmap(@ullable DisplayMetrics display, int width, int height, @NonNull Config config, boolean hasAlpha)1078     public static Bitmap createBitmap(@Nullable DisplayMetrics display, int width, int height,
1079             @NonNull Config config, boolean hasAlpha) {
1080         return createBitmap(display, width, height, config, hasAlpha,
1081                 ColorSpace.get(ColorSpace.Named.SRGB));
1082     }
1083 
1084     /**
1085      * Returns a mutable bitmap with the specified width and height.  Its
1086      * initial density is determined from the given {@link DisplayMetrics}.
1087      * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
1088      * color space.
1089      *
1090      * @param display  Display metrics for the display this bitmap will be
1091      *                 drawn on.
1092      * @param width    The width of the bitmap
1093      * @param height   The height of the bitmap
1094      * @param config   The bitmap config to create.
1095      * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
1096      *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
1097      *                 instead of transparent.
1098      * @param colorSpace The color space of the bitmap. If the config is {@link Config#RGBA_F16}
1099      *                   and {@link ColorSpace.Named#SRGB sRGB} or
1100      *                   {@link ColorSpace.Named#LINEAR_SRGB Linear sRGB} is provided then the
1101      *                   corresponding extended range variant is assumed.
1102      *
1103      * @throws IllegalArgumentException if the width or height are <= 0, if
1104      *         Config is Config.HARDWARE (because hardware bitmaps are always
1105      *         immutable), if the specified color space is not {@link ColorSpace.Model#RGB RGB},
1106      *         if the specified color space's transfer function is not an
1107      *         {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}, or if
1108      *         the color space is null
1109      */
createBitmap(@ullable DisplayMetrics display, int width, int height, @NonNull Config config, boolean hasAlpha, @NonNull ColorSpace colorSpace)1110     public static Bitmap createBitmap(@Nullable DisplayMetrics display, int width, int height,
1111             @NonNull Config config, boolean hasAlpha, @NonNull ColorSpace colorSpace) {
1112         if (width <= 0 || height <= 0) {
1113             throw new IllegalArgumentException("width and height must be > 0");
1114         }
1115         if (config == Config.HARDWARE) {
1116             throw new IllegalArgumentException("can't create mutable bitmap with Config.HARDWARE");
1117         }
1118         if (colorSpace == null && config != Config.ALPHA_8) {
1119             throw new IllegalArgumentException("can't create bitmap without a color space");
1120         }
1121 
1122         Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true,
1123                 colorSpace == null ? 0 : colorSpace.getNativeInstance());
1124 
1125         if (display != null) {
1126             bm.mDensity = display.densityDpi;
1127         }
1128         bm.setHasAlpha(hasAlpha);
1129         if ((config == Config.ARGB_8888 || config == Config.RGBA_F16) && !hasAlpha) {
1130             nativeErase(bm.mNativePtr, 0xff000000);
1131         }
1132         // No need to initialize the bitmap to zeroes with other configs;
1133         // it is backed by a VM byte array which is by definition preinitialized
1134         // to all zeroes.
1135         return bm;
1136     }
1137 
1138     /**
1139      * Returns a immutable bitmap with the specified width and height, with each
1140      * pixel value set to the corresponding value in the colors array.  Its
1141      * initial density is as per {@link #getDensity}. The newly created
1142      * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
1143      *
1144      * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
1145      * @param offset   Number of values to skip before the first color in the
1146      *                 array of colors.
1147      * @param stride   Number of colors in the array between rows (must be >=
1148      *                 width or <= -width).
1149      * @param width    The width of the bitmap
1150      * @param height   The height of the bitmap
1151      * @param config   The bitmap config to create. If the config does not
1152      *                 support per-pixel alpha (e.g. RGB_565), then the alpha
1153      *                 bytes in the colors[] will be ignored (assumed to be FF)
1154      * @throws IllegalArgumentException if the width or height are <= 0, or if
1155      *         the color array's length is less than the number of pixels.
1156      */
createBitmap(@onNull @olorInt int[] colors, int offset, int stride, int width, int height, @NonNull Config config)1157     public static Bitmap createBitmap(@NonNull @ColorInt int[] colors, int offset, int stride,
1158             int width, int height, @NonNull Config config) {
1159         return createBitmap(null, colors, offset, stride, width, height, config);
1160     }
1161 
1162     /**
1163      * Returns a immutable bitmap with the specified width and height, with each
1164      * pixel value set to the corresponding value in the colors array.  Its
1165      * initial density is determined from the given {@link DisplayMetrics}.
1166      * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
1167      * color space.
1168      *
1169      * @param display  Display metrics for the display this bitmap will be
1170      *                 drawn on.
1171      * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
1172      * @param offset   Number of values to skip before the first color in the
1173      *                 array of colors.
1174      * @param stride   Number of colors in the array between rows (must be >=
1175      *                 width or <= -width).
1176      * @param width    The width of the bitmap
1177      * @param height   The height of the bitmap
1178      * @param config   The bitmap config to create. If the config does not
1179      *                 support per-pixel alpha (e.g. RGB_565), then the alpha
1180      *                 bytes in the colors[] will be ignored (assumed to be FF)
1181      * @throws IllegalArgumentException if the width or height are <= 0, or if
1182      *         the color array's length is less than the number of pixels.
1183      */
createBitmap(@onNull DisplayMetrics display, @NonNull @ColorInt int[] colors, int offset, int stride, int width, int height, @NonNull Config config)1184     public static Bitmap createBitmap(@NonNull DisplayMetrics display,
1185             @NonNull @ColorInt int[] colors, int offset, int stride,
1186             int width, int height, @NonNull Config config) {
1187 
1188         checkWidthHeight(width, height);
1189         if (Math.abs(stride) < width) {
1190             throw new IllegalArgumentException("abs(stride) must be >= width");
1191         }
1192         int lastScanline = offset + (height - 1) * stride;
1193         int length = colors.length;
1194         if (offset < 0 || (offset + width > length) || lastScanline < 0 ||
1195                 (lastScanline + width > length)) {
1196             throw new ArrayIndexOutOfBoundsException();
1197         }
1198         if (width <= 0 || height <= 0) {
1199             throw new IllegalArgumentException("width and height must be > 0");
1200         }
1201         ColorSpace sRGB = ColorSpace.get(ColorSpace.Named.SRGB);
1202         Bitmap bm = nativeCreate(colors, offset, stride, width, height,
1203                             config.nativeInt, false, sRGB.getNativeInstance());
1204         if (display != null) {
1205             bm.mDensity = display.densityDpi;
1206         }
1207         return bm;
1208     }
1209 
1210     /**
1211      * Returns a immutable bitmap with the specified width and height, with each
1212      * pixel value set to the corresponding value in the colors array.  Its
1213      * initial density is as per {@link #getDensity}. The newly created
1214      * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
1215      *
1216      * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
1217      *                 This array must be at least as large as width * height.
1218      * @param width    The width of the bitmap
1219      * @param height   The height of the bitmap
1220      * @param config   The bitmap config to create. If the config does not
1221      *                 support per-pixel alpha (e.g. RGB_565), then the alpha
1222      *                 bytes in the colors[] will be ignored (assumed to be FF)
1223      * @throws IllegalArgumentException if the width or height are <= 0, or if
1224      *         the color array's length is less than the number of pixels.
1225      */
createBitmap(@onNull @olorInt int[] colors, int width, int height, Config config)1226     public static Bitmap createBitmap(@NonNull @ColorInt int[] colors,
1227             int width, int height, Config config) {
1228         return createBitmap(null, colors, 0, width, width, height, config);
1229     }
1230 
1231     /**
1232      * Returns a immutable bitmap with the specified width and height, with each
1233      * pixel value set to the corresponding value in the colors array.  Its
1234      * initial density is determined from the given {@link DisplayMetrics}.
1235      * The newly created bitmap is in the {@link ColorSpace.Named#SRGB sRGB}
1236      * color space.
1237      *
1238      * @param display  Display metrics for the display this bitmap will be
1239      *                 drawn on.
1240      * @param colors   Array of sRGB {@link Color colors} used to initialize the pixels.
1241      *                 This array must be at least as large as width * height.
1242      * @param width    The width of the bitmap
1243      * @param height   The height of the bitmap
1244      * @param config   The bitmap config to create. If the config does not
1245      *                 support per-pixel alpha (e.g. RGB_565), then the alpha
1246      *                 bytes in the colors[] will be ignored (assumed to be FF)
1247      * @throws IllegalArgumentException if the width or height are <= 0, or if
1248      *         the color array's length is less than the number of pixels.
1249      */
createBitmap(@ullable DisplayMetrics display, @NonNull @ColorInt int colors[], int width, int height, @NonNull Config config)1250     public static Bitmap createBitmap(@Nullable DisplayMetrics display,
1251             @NonNull @ColorInt int colors[], int width, int height, @NonNull Config config) {
1252         return createBitmap(display, colors, 0, width, width, height, config);
1253     }
1254 
1255     /**
1256      * Creates a Bitmap from the given {@link Picture} source of recorded drawing commands.
1257      *
1258      * Equivalent to calling {@link #createBitmap(Picture, int, int, Config)} with
1259      * width and height the same as the Picture's width and height and a Config.HARDWARE
1260      * config.
1261      *
1262      * @param source The recorded {@link Picture} of drawing commands that will be
1263      *               drawn into the returned Bitmap.
1264      * @return An immutable bitmap with a HARDWARE config whose contents are created
1265      * from the recorded drawing commands in the Picture source.
1266      */
createBitmap(@onNull Picture source)1267     public static @NonNull Bitmap createBitmap(@NonNull Picture source) {
1268         return createBitmap(source, source.getWidth(), source.getHeight(), Config.HARDWARE);
1269     }
1270 
1271     /**
1272      * Creates a Bitmap from the given {@link Picture} source of recorded drawing commands.
1273      *
1274      * The bitmap will be immutable with the given width and height. If the width and height
1275      * are not the same as the Picture's width & height, the Picture will be scaled to
1276      * fit the given width and height.
1277      *
1278      * @param source The recorded {@link Picture} of drawing commands that will be
1279      *               drawn into the returned Bitmap.
1280      * @param width The width of the bitmap to create. The picture's width will be
1281      *              scaled to match if necessary.
1282      * @param height The height of the bitmap to create. The picture's height will be
1283      *              scaled to match if necessary.
1284      * @param config The {@link Config} of the created bitmap.
1285      *
1286      * @return An immutable bitmap with a configuration specified by the config parameter
1287      */
createBitmap(@onNull Picture source, int width, int height, @NonNull Config config)1288     public static @NonNull Bitmap createBitmap(@NonNull Picture source, int width, int height,
1289             @NonNull Config config) {
1290         if (width <= 0 || height <= 0) {
1291             throw new IllegalArgumentException("width & height must be > 0");
1292         }
1293         if (config == null) {
1294             throw new IllegalArgumentException("Config must not be null");
1295         }
1296         source.endRecording();
1297         if (source.requiresHardwareAcceleration() && config != Config.HARDWARE) {
1298             StrictMode.noteSlowCall("GPU readback");
1299         }
1300         if (config == Config.HARDWARE || source.requiresHardwareAcceleration()) {
1301             final RenderNode node = RenderNode.create("BitmapTemporary", null);
1302             node.setLeftTopRightBottom(0, 0, width, height);
1303             node.setClipToBounds(false);
1304             node.setForceDarkAllowed(false);
1305             final RecordingCanvas canvas = node.beginRecording(width, height);
1306             if (source.getWidth() != width || source.getHeight() != height) {
1307                 canvas.scale(width / (float) source.getWidth(),
1308                         height / (float) source.getHeight());
1309             }
1310             canvas.drawPicture(source);
1311             node.endRecording();
1312             Bitmap bitmap = ThreadedRenderer.createHardwareBitmap(node, width, height);
1313             if (config != Config.HARDWARE) {
1314                 bitmap = bitmap.copy(config, false);
1315             }
1316             return bitmap;
1317         } else {
1318             Bitmap bitmap = Bitmap.createBitmap(width, height, config);
1319             Canvas canvas = new Canvas(bitmap);
1320             if (source.getWidth() != width || source.getHeight() != height) {
1321                 canvas.scale(width / (float) source.getWidth(),
1322                         height / (float) source.getHeight());
1323             }
1324             canvas.drawPicture(source);
1325             canvas.setBitmap(null);
1326             bitmap.setImmutable();
1327             return bitmap;
1328         }
1329     }
1330 
1331     /**
1332      * Returns an optional array of private data, used by the UI system for
1333      * some bitmaps. Not intended to be called by applications.
1334      */
getNinePatchChunk()1335     public byte[] getNinePatchChunk() {
1336         return mNinePatchChunk;
1337     }
1338 
1339     /**
1340      * Populates a rectangle with the bitmap's optical insets.
1341      *
1342      * @param outInsets Rect to populate with optical insets
1343      * @hide
1344      */
getOpticalInsets(@onNull Rect outInsets)1345     public void getOpticalInsets(@NonNull Rect outInsets) {
1346         if (mNinePatchInsets == null) {
1347             outInsets.setEmpty();
1348         } else {
1349             outInsets.set(mNinePatchInsets.opticalRect);
1350         }
1351     }
1352 
1353     /** @hide */
getNinePatchInsets()1354     public NinePatch.InsetStruct getNinePatchInsets() {
1355         return mNinePatchInsets;
1356     }
1357 
1358     /**
1359      * Specifies the known formats a bitmap can be compressed into
1360      */
1361     public enum CompressFormat {
1362         /**
1363          * Compress to the JPEG format. {@code quality} of {@code 0} means
1364          * compress for the smallest size. {@code 100} means compress for max
1365          * visual quality.
1366          */
1367         JPEG          (0),
1368         /**
1369          * Compress to the PNG format. PNG is lossless, so {@code quality} is
1370          * ignored.
1371          */
1372         PNG           (1),
1373         /**
1374          * Compress to the WEBP format. {@code quality} of {@code 0} means
1375          * compress for the smallest size. {@code 100} means compress for max
1376          * visual quality. As of {@link android.os.Build.VERSION_CODES#Q}, a
1377          * value of {@code 100} results in a file in the lossless WEBP format.
1378          * Otherwise the file will be in the lossy WEBP format.
1379          *
1380          * @deprecated in favor of the more explicit
1381          *             {@link CompressFormat#WEBP_LOSSY} and
1382          *             {@link CompressFormat#WEBP_LOSSLESS}.
1383          */
1384         @Deprecated
1385         WEBP          (2),
1386         /**
1387          * Compress to the WEBP lossy format. {@code quality} of {@code 0} means
1388          * compress for the smallest size. {@code 100} means compress for max
1389          * visual quality.
1390          */
1391         WEBP_LOSSY    (3),
1392         /**
1393          * Compress to the WEBP lossless format. {@code quality} refers to how
1394          * much effort to put into compression. A value of {@code 0} means to
1395          * compress quickly, resulting in a relatively large file size.
1396          * {@code 100} means to spend more time compressing, resulting in a
1397          * smaller file.
1398          */
1399         WEBP_LOSSLESS (4);
1400 
CompressFormat(int nativeInt)1401         CompressFormat(int nativeInt) {
1402             this.nativeInt = nativeInt;
1403         }
1404         final int nativeInt;
1405     }
1406 
1407     /**
1408      * Number of bytes of temp storage we use for communicating between the
1409      * native compressor and the java OutputStream.
1410      */
1411     private final static int WORKING_COMPRESS_STORAGE = 4096;
1412 
1413     /**
1414      * Write a compressed version of the bitmap to the specified outputstream.
1415      * If this returns true, the bitmap can be reconstructed by passing a
1416      * corresponding inputstream to BitmapFactory.decodeStream(). Note: not
1417      * all Formats support all bitmap configs directly, so it is possible that
1418      * the returned bitmap from BitmapFactory could be in a different bitdepth,
1419      * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque
1420      * pixels).
1421      *
1422      * @param format   The format of the compressed image
1423      * @param quality  Hint to the compressor, 0-100. The value is interpreted
1424      *                 differently depending on the {@link CompressFormat}.
1425      * @param stream   The outputstream to write the compressed data.
1426      * @return true if successfully compressed to the specified stream.
1427      */
1428     @WorkerThread
compress(CompressFormat format, int quality, OutputStream stream)1429     public boolean compress(CompressFormat format, int quality, OutputStream stream) {
1430         checkRecycled("Can't compress a recycled bitmap");
1431         // do explicit check before calling the native method
1432         if (stream == null) {
1433             throw new NullPointerException();
1434         }
1435         if (quality < 0 || quality > 100) {
1436             throw new IllegalArgumentException("quality must be 0..100");
1437         }
1438         StrictMode.noteSlowCall("Compression of a bitmap is slow");
1439         Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress");
1440         boolean result = nativeCompress(mNativePtr, format.nativeInt,
1441                 quality, stream, new byte[WORKING_COMPRESS_STORAGE]);
1442         Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1443         return result;
1444     }
1445 
1446     /**
1447      * Returns true if the bitmap is marked as mutable (i.e.&nbsp;can be drawn into)
1448      */
isMutable()1449     public final boolean isMutable() {
1450         return !nativeIsImmutable(mNativePtr);
1451     }
1452 
1453     /**
1454      * Marks the Bitmap as immutable. Further modifications to this Bitmap are disallowed.
1455      * After this method is called, this Bitmap cannot be made mutable again and subsequent calls
1456      * to {@link #reconfigure(int, int, Config)}, {@link #setPixel(int, int, int)},
1457      * {@link #setPixels(int[], int, int, int, int, int, int)} and {@link #eraseColor(int)} will
1458      * fail and throw an IllegalStateException.
1459      *
1460      * @hide
1461      */
setImmutable()1462     public void setImmutable() {
1463         if (isMutable()) {
1464             nativeSetImmutable(mNativePtr);
1465         }
1466     }
1467 
1468     /**
1469      * <p>Indicates whether pixels stored in this bitmaps are stored pre-multiplied.
1470      * When a pixel is pre-multiplied, the RGB components have been multiplied by
1471      * the alpha component. For instance, if the original color is a 50%
1472      * translucent red <code>(128, 255, 0, 0)</code>, the pre-multiplied form is
1473      * <code>(128, 128, 0, 0)</code>.</p>
1474      *
1475      * <p>This method always returns false if {@link #getConfig()} is
1476      * {@link Bitmap.Config#RGB_565}.</p>
1477      *
1478      * <p>The return value is undefined if {@link #getConfig()} is
1479      * {@link Bitmap.Config#ALPHA_8}.</p>
1480      *
1481      * <p>This method only returns true if {@link #hasAlpha()} returns true.
1482      * A bitmap with no alpha channel can be used both as a pre-multiplied and
1483      * as a non pre-multiplied bitmap.</p>
1484      *
1485      * <p>Only pre-multiplied bitmaps may be drawn by the view system or
1486      * {@link Canvas}. If a non-pre-multiplied bitmap with an alpha channel is
1487      * drawn to a Canvas, a RuntimeException will be thrown.</p>
1488      *
1489      * @return true if the underlying pixels have been pre-multiplied, false
1490      *         otherwise
1491      *
1492      * @see Bitmap#setPremultiplied(boolean)
1493      * @see BitmapFactory.Options#inPremultiplied
1494      */
isPremultiplied()1495     public final boolean isPremultiplied() {
1496         if (mRecycled) {
1497             Log.w(TAG, "Called isPremultiplied() on a recycle()'d bitmap! This is undefined behavior!");
1498         }
1499         return nativeIsPremultiplied(mNativePtr);
1500     }
1501 
1502     /**
1503      * Sets whether the bitmap should treat its data as pre-multiplied.
1504      *
1505      * <p>Bitmaps are always treated as pre-multiplied by the view system and
1506      * {@link Canvas} for performance reasons. Storing un-pre-multiplied data in
1507      * a Bitmap (through {@link #setPixel}, {@link #setPixels}, or {@link
1508      * BitmapFactory.Options#inPremultiplied BitmapFactory.Options.inPremultiplied})
1509      * can lead to incorrect blending if drawn by the framework.</p>
1510      *
1511      * <p>This method will not affect the behavior of a bitmap without an alpha
1512      * channel, or if {@link #hasAlpha()} returns false.</p>
1513      *
1514      * <p>Calling {@link #createBitmap} or {@link #createScaledBitmap} with a source
1515      * Bitmap whose colors are not pre-multiplied may result in a RuntimeException,
1516      * since those functions require drawing the source, which is not supported for
1517      * un-pre-multiplied Bitmaps.</p>
1518      *
1519      * @see Bitmap#isPremultiplied()
1520      * @see BitmapFactory.Options#inPremultiplied
1521      */
setPremultiplied(boolean premultiplied)1522     public final void setPremultiplied(boolean premultiplied) {
1523         checkRecycled("setPremultiplied called on a recycled bitmap");
1524         mRequestPremultiplied = premultiplied;
1525         nativeSetPremultiplied(mNativePtr, premultiplied);
1526     }
1527 
1528     /** Returns the bitmap's width */
getWidth()1529     public final int getWidth() {
1530         if (mRecycled) {
1531             Log.w(TAG, "Called getWidth() on a recycle()'d bitmap! This is undefined behavior!");
1532         }
1533         return mWidth;
1534     }
1535 
1536     /** Returns the bitmap's height */
getHeight()1537     public final int getHeight() {
1538         if (mRecycled) {
1539             Log.w(TAG, "Called getHeight() on a recycle()'d bitmap! This is undefined behavior!");
1540         }
1541         return mHeight;
1542     }
1543 
1544     /**
1545      * Convenience for calling {@link #getScaledWidth(int)} with the target
1546      * density of the given {@link Canvas}.
1547      */
getScaledWidth(Canvas canvas)1548     public int getScaledWidth(Canvas canvas) {
1549         return scaleFromDensity(getWidth(), mDensity, canvas.mDensity);
1550     }
1551 
1552     /**
1553      * Convenience for calling {@link #getScaledHeight(int)} with the target
1554      * density of the given {@link Canvas}.
1555      */
getScaledHeight(Canvas canvas)1556     public int getScaledHeight(Canvas canvas) {
1557         return scaleFromDensity(getHeight(), mDensity, canvas.mDensity);
1558     }
1559 
1560     /**
1561      * Convenience for calling {@link #getScaledWidth(int)} with the target
1562      * density of the given {@link DisplayMetrics}.
1563      */
getScaledWidth(DisplayMetrics metrics)1564     public int getScaledWidth(DisplayMetrics metrics) {
1565         return scaleFromDensity(getWidth(), mDensity, metrics.densityDpi);
1566     }
1567 
1568     /**
1569      * Convenience for calling {@link #getScaledHeight(int)} with the target
1570      * density of the given {@link DisplayMetrics}.
1571      */
getScaledHeight(DisplayMetrics metrics)1572     public int getScaledHeight(DisplayMetrics metrics) {
1573         return scaleFromDensity(getHeight(), mDensity, metrics.densityDpi);
1574     }
1575 
1576     /**
1577      * Convenience method that returns the width of this bitmap divided
1578      * by the density scale factor.
1579      *
1580      * Returns the bitmap's width multiplied by the ratio of the target density to the bitmap's
1581      * source density
1582      *
1583      * @param targetDensity The density of the target canvas of the bitmap.
1584      * @return The scaled width of this bitmap, according to the density scale factor.
1585      */
getScaledWidth(int targetDensity)1586     public int getScaledWidth(int targetDensity) {
1587         return scaleFromDensity(getWidth(), mDensity, targetDensity);
1588     }
1589 
1590     /**
1591      * Convenience method that returns the height of this bitmap divided
1592      * by the density scale factor.
1593      *
1594      * Returns the bitmap's height multiplied by the ratio of the target density to the bitmap's
1595      * source density
1596      *
1597      * @param targetDensity The density of the target canvas of the bitmap.
1598      * @return The scaled height of this bitmap, according to the density scale factor.
1599      */
getScaledHeight(int targetDensity)1600     public int getScaledHeight(int targetDensity) {
1601         return scaleFromDensity(getHeight(), mDensity, targetDensity);
1602     }
1603 
1604     /**
1605      * @hide
1606      */
1607     @UnsupportedAppUsage
scaleFromDensity(int size, int sdensity, int tdensity)1608     static public int scaleFromDensity(int size, int sdensity, int tdensity) {
1609         if (sdensity == DENSITY_NONE || tdensity == DENSITY_NONE || sdensity == tdensity) {
1610             return size;
1611         }
1612 
1613         // Scale by tdensity / sdensity, rounding up.
1614         return ((size * tdensity) + (sdensity >> 1)) / sdensity;
1615     }
1616 
1617     /**
1618      * Return the number of bytes between rows in the bitmap's pixels. Note that
1619      * this refers to the pixels as stored natively by the bitmap. If you call
1620      * getPixels() or setPixels(), then the pixels are uniformly treated as
1621      * 32bit values, packed according to the Color class.
1622      *
1623      * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, this method
1624      * should not be used to calculate the memory usage of the bitmap. Instead,
1625      * see {@link #getAllocationByteCount()}.
1626      *
1627      * @return number of bytes between rows of the native bitmap pixels.
1628      */
getRowBytes()1629     public final int getRowBytes() {
1630         if (mRecycled) {
1631             Log.w(TAG, "Called getRowBytes() on a recycle()'d bitmap! This is undefined behavior!");
1632         }
1633         return nativeRowBytes(mNativePtr);
1634     }
1635 
1636     /**
1637      * Returns the minimum number of bytes that can be used to store this bitmap's pixels.
1638      *
1639      * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can
1640      * no longer be used to determine memory usage of a bitmap. See {@link
1641      * #getAllocationByteCount()}.</p>
1642      */
getByteCount()1643     public final int getByteCount() {
1644         if (mRecycled) {
1645             Log.w(TAG, "Called getByteCount() on a recycle()'d bitmap! "
1646                     + "This is undefined behavior!");
1647             return 0;
1648         }
1649         // int result permits bitmaps up to 46,340 x 46,340
1650         return getRowBytes() * getHeight();
1651     }
1652 
1653     /**
1654      * Returns the size of the allocated memory used to store this bitmap's pixels.
1655      *
1656      * <p>This can be larger than the result of {@link #getByteCount()} if a bitmap is reused to
1657      * decode other bitmaps of smaller size, or by manual reconfiguration. See {@link
1658      * #reconfigure(int, int, Config)}, {@link #setWidth(int)}, {@link #setHeight(int)}, {@link
1659      * #setConfig(Bitmap.Config)}, and {@link BitmapFactory.Options#inBitmap
1660      * BitmapFactory.Options.inBitmap}. If a bitmap is not modified in this way, this value will be
1661      * the same as that returned by {@link #getByteCount()}.</p>
1662      *
1663      * <p>This value will not change over the lifetime of a Bitmap.</p>
1664      *
1665      * @see #reconfigure(int, int, Config)
1666      */
getAllocationByteCount()1667     public final int getAllocationByteCount() {
1668         if (mRecycled) {
1669             Log.w(TAG, "Called getAllocationByteCount() on a recycle()'d bitmap! "
1670                     + "This is undefined behavior!");
1671             return 0;
1672         }
1673         return nativeGetAllocationByteCount(mNativePtr);
1674     }
1675 
1676     /**
1677      * If the bitmap's internal config is in one of the public formats, return
1678      * that config, otherwise return null.
1679      */
getConfig()1680     public final Config getConfig() {
1681         if (mRecycled) {
1682             Log.w(TAG, "Called getConfig() on a recycle()'d bitmap! This is undefined behavior!");
1683         }
1684         return Config.nativeToConfig(nativeConfig(mNativePtr));
1685     }
1686 
1687     /** Returns true if the bitmap's config supports per-pixel alpha, and
1688      * if the pixels may contain non-opaque alpha values. For some configs,
1689      * this is always false (e.g. RGB_565), since they do not support per-pixel
1690      * alpha. However, for configs that do, the bitmap may be flagged to be
1691      * known that all of its pixels are opaque. In this case hasAlpha() will
1692      * also return false. If a config such as ARGB_8888 is not so flagged,
1693      * it will return true by default.
1694      */
hasAlpha()1695     public final boolean hasAlpha() {
1696         if (mRecycled) {
1697             Log.w(TAG, "Called hasAlpha() on a recycle()'d bitmap! This is undefined behavior!");
1698         }
1699         return nativeHasAlpha(mNativePtr);
1700     }
1701 
1702     /**
1703      * Tell the bitmap if all of the pixels are known to be opaque (false)
1704      * or if some of the pixels may contain non-opaque alpha values (true).
1705      * Note, for some configs (e.g. RGB_565) this call is ignored, since it
1706      * does not support per-pixel alpha values.
1707      *
1708      * This is meant as a drawing hint, as in some cases a bitmap that is known
1709      * to be opaque can take a faster drawing case than one that may have
1710      * non-opaque per-pixel alpha values.
1711      */
setHasAlpha(boolean hasAlpha)1712     public void setHasAlpha(boolean hasAlpha) {
1713         checkRecycled("setHasAlpha called on a recycled bitmap");
1714         nativeSetHasAlpha(mNativePtr, hasAlpha, mRequestPremultiplied);
1715     }
1716 
1717     /**
1718      * Indicates whether the renderer responsible for drawing this
1719      * bitmap should attempt to use mipmaps when this bitmap is drawn
1720      * scaled down.
1721      *
1722      * If you know that you are going to draw this bitmap at less than
1723      * 50% of its original size, you may be able to obtain a higher
1724      * quality
1725      *
1726      * This property is only a suggestion that can be ignored by the
1727      * renderer. It is not guaranteed to have any effect.
1728      *
1729      * @return true if the renderer should attempt to use mipmaps,
1730      *         false otherwise
1731      *
1732      * @see #setHasMipMap(boolean)
1733      */
hasMipMap()1734     public final boolean hasMipMap() {
1735         if (mRecycled) {
1736             Log.w(TAG, "Called hasMipMap() on a recycle()'d bitmap! This is undefined behavior!");
1737         }
1738         return nativeHasMipMap(mNativePtr);
1739     }
1740 
1741     /**
1742      * Set a hint for the renderer responsible for drawing this bitmap
1743      * indicating that it should attempt to use mipmaps when this bitmap
1744      * is drawn scaled down.
1745      *
1746      * If you know that you are going to draw this bitmap at less than
1747      * 50% of its original size, you may be able to obtain a higher
1748      * quality by turning this property on.
1749      *
1750      * Note that if the renderer respects this hint it might have to
1751      * allocate extra memory to hold the mipmap levels for this bitmap.
1752      *
1753      * This property is only a suggestion that can be ignored by the
1754      * renderer. It is not guaranteed to have any effect.
1755      *
1756      * @param hasMipMap indicates whether the renderer should attempt
1757      *                  to use mipmaps
1758      *
1759      * @see #hasMipMap()
1760      */
setHasMipMap(boolean hasMipMap)1761     public final void setHasMipMap(boolean hasMipMap) {
1762         checkRecycled("setHasMipMap called on a recycled bitmap");
1763         nativeSetHasMipMap(mNativePtr, hasMipMap);
1764     }
1765 
1766     /**
1767      * Returns the color space associated with this bitmap. If the color
1768      * space is unknown, this method returns null.
1769      */
1770     @Nullable
getColorSpace()1771     public final ColorSpace getColorSpace() {
1772         checkRecycled("getColorSpace called on a recycled bitmap");
1773         if (mColorSpace == null) {
1774             mColorSpace = nativeComputeColorSpace(mNativePtr);
1775         }
1776         return mColorSpace;
1777     }
1778 
1779     /**
1780      * <p>Modifies the bitmap to have the specified {@link ColorSpace}, without
1781      * affecting the underlying allocation backing the bitmap.</p>
1782      *
1783      * <p>This affects how the framework will interpret the color at each pixel. A bitmap
1784      * with {@link Config#ALPHA_8} never has a color space, since a color space does not
1785      * affect the alpha channel. Other {@code Config}s must always have a non-null
1786      * {@code ColorSpace}.</p>
1787      *
1788      * @throws IllegalArgumentException If the specified color space is {@code null}, not
1789      *         {@link ColorSpace.Model#RGB RGB}, has a transfer function that is not an
1790      *         {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}, or whose
1791      *         components min/max values reduce the numerical range compared to the
1792      *         previously assigned color space.
1793      *
1794      * @throws IllegalArgumentException If the {@code Config} (returned by {@link #getConfig()})
1795      *         is {@link Config#ALPHA_8}.
1796      *
1797      * @param colorSpace to assign to the bitmap
1798      */
setColorSpace(@onNull ColorSpace colorSpace)1799     public void setColorSpace(@NonNull ColorSpace colorSpace) {
1800         checkRecycled("setColorSpace called on a recycled bitmap");
1801         if (colorSpace == null) {
1802             throw new IllegalArgumentException("The colorSpace cannot be set to null");
1803         }
1804 
1805         if (getConfig() == Config.ALPHA_8) {
1806             throw new IllegalArgumentException("Cannot set a ColorSpace on ALPHA_8");
1807         }
1808 
1809         // Keep track of the old ColorSpace for comparison, and so we can reset it in case of an
1810         // Exception.
1811         final ColorSpace oldColorSpace = getColorSpace();
1812         nativeSetColorSpace(mNativePtr, colorSpace.getNativeInstance());
1813 
1814         // This will update mColorSpace. It may not be the same as |colorSpace|, e.g. if we
1815         // corrected it because the Bitmap is F16.
1816         mColorSpace = null;
1817         final ColorSpace newColorSpace = getColorSpace();
1818 
1819         try {
1820             if (oldColorSpace.getComponentCount() != newColorSpace.getComponentCount()) {
1821                 throw new IllegalArgumentException("The new ColorSpace must have the same "
1822                         + "component count as the current ColorSpace");
1823             } else {
1824                 for (int i = 0; i < oldColorSpace.getComponentCount(); i++) {
1825                     if (oldColorSpace.getMinValue(i) < newColorSpace.getMinValue(i)) {
1826                         throw new IllegalArgumentException("The new ColorSpace cannot increase the "
1827                                 + "minimum value for any of the components compared to the current "
1828                                 + "ColorSpace. To perform this type of conversion create a new "
1829                                 + "Bitmap in the desired ColorSpace and draw this Bitmap into it.");
1830                     }
1831                     if (oldColorSpace.getMaxValue(i) > newColorSpace.getMaxValue(i)) {
1832                         throw new IllegalArgumentException("The new ColorSpace cannot decrease the "
1833                                 + "maximum value for any of the components compared to the current "
1834                                 + "ColorSpace/ To perform this type of conversion create a new "
1835                                 + "Bitmap in the desired ColorSpace and draw this Bitmap into it.");
1836                     }
1837                 }
1838             }
1839         } catch (IllegalArgumentException e) {
1840             // Undo the change to the ColorSpace.
1841             mColorSpace = oldColorSpace;
1842             nativeSetColorSpace(mNativePtr, mColorSpace.getNativeInstance());
1843             throw e;
1844         }
1845     }
1846 
1847     /**
1848      * Fills the bitmap's pixels with the specified {@link Color}.
1849      *
1850      * @throws IllegalStateException if the bitmap is not mutable.
1851      */
eraseColor(@olorInt int c)1852     public void eraseColor(@ColorInt int c) {
1853         checkRecycled("Can't erase a recycled bitmap");
1854         if (!isMutable()) {
1855             throw new IllegalStateException("cannot erase immutable bitmaps");
1856         }
1857         nativeErase(mNativePtr, c);
1858     }
1859 
1860     /**
1861      * Fills the bitmap's pixels with the specified {@code ColorLong}.
1862      *
1863      * @param color The color to fill as packed by the {@link Color} class.
1864      * @throws IllegalStateException if the bitmap is not mutable.
1865      * @throws IllegalArgumentException if the color space encoded in the
1866      *                                  {@code ColorLong} is invalid or unknown.
1867      *
1868      */
eraseColor(@olorLong long color)1869     public void eraseColor(@ColorLong long color) {
1870         checkRecycled("Can't erase a recycled bitmap");
1871         if (!isMutable()) {
1872             throw new IllegalStateException("cannot erase immutable bitmaps");
1873         }
1874 
1875         ColorSpace cs = Color.colorSpace(color);
1876         nativeErase(mNativePtr, cs.getNativeInstance(), color);
1877     }
1878 
1879     /**
1880      * Returns the {@link Color} at the specified location. Throws an exception
1881      * if x or y are out of bounds (negative or >= to the width or height
1882      * respectively). The returned color is a non-premultiplied ARGB value in
1883      * the {@link ColorSpace.Named#SRGB sRGB} color space.
1884      *
1885      * @param x    The x coordinate (0...width-1) of the pixel to return
1886      * @param y    The y coordinate (0...height-1) of the pixel to return
1887      * @return     The argb {@link Color} at the specified coordinate
1888      * @throws IllegalArgumentException if x, y exceed the bitmap's bounds
1889      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
1890      */
1891     @ColorInt
getPixel(int x, int y)1892     public int getPixel(int x, int y) {
1893         checkRecycled("Can't call getPixel() on a recycled bitmap");
1894         checkHardware("unable to getPixel(), "
1895                 + "pixel access is not supported on Config#HARDWARE bitmaps");
1896         checkPixelAccess(x, y);
1897         return nativeGetPixel(mNativePtr, x, y);
1898     }
1899 
clamp(float value, @NonNull ColorSpace cs, int index)1900     private static float clamp(float value, @NonNull ColorSpace cs, int index) {
1901         return Math.max(Math.min(value, cs.getMaxValue(index)), cs.getMinValue(index));
1902     }
1903 
1904     /**
1905      * Returns the {@link Color} at the specified location. Throws an exception
1906      * if x or y are out of bounds (negative or >= to the width or height
1907      * respectively).
1908      *
1909      * @param x    The x coordinate (0...width-1) of the pixel to return
1910      * @param y    The y coordinate (0...height-1) of the pixel to return
1911      * @return     The {@link Color} at the specified coordinate
1912      * @throws IllegalArgumentException if x, y exceed the bitmap's bounds
1913      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
1914      *
1915      */
1916     @NonNull
getColor(int x, int y)1917     public Color getColor(int x, int y) {
1918         checkRecycled("Can't call getColor() on a recycled bitmap");
1919         checkHardware("unable to getColor(), "
1920                 + "pixel access is not supported on Config#HARDWARE bitmaps");
1921         checkPixelAccess(x, y);
1922 
1923         final ColorSpace cs = getColorSpace();
1924         if (cs.equals(ColorSpace.get(ColorSpace.Named.SRGB))) {
1925             return Color.valueOf(nativeGetPixel(mNativePtr, x, y));
1926         }
1927         // The returned value is in kRGBA_F16_SkColorType, which is packed as
1928         // four half-floats, r,g,b,a.
1929         long rgba = nativeGetColor(mNativePtr, x, y);
1930         float r = Half.toFloat((short) ((rgba >>  0) & 0xffff));
1931         float g = Half.toFloat((short) ((rgba >> 16) & 0xffff));
1932         float b = Half.toFloat((short) ((rgba >> 32) & 0xffff));
1933         float a = Half.toFloat((short) ((rgba >> 48) & 0xffff));
1934 
1935         // Skia may draw outside of the numerical range of the colorSpace.
1936         // Clamp to get an expected value.
1937         return Color.valueOf(clamp(r, cs, 0), clamp(g, cs, 1), clamp(b, cs, 2), a, cs);
1938     }
1939 
1940     /**
1941      * Returns in pixels[] a copy of the data in the bitmap. Each value is
1942      * a packed int representing a {@link Color}. The stride parameter allows
1943      * the caller to allow for gaps in the returned pixels array between
1944      * rows. For normal packed results, just pass width for the stride value.
1945      * The returned colors are non-premultiplied ARGB values in the
1946      * {@link ColorSpace.Named#SRGB sRGB} color space.
1947      *
1948      * @param pixels   The array to receive the bitmap's colors
1949      * @param offset   The first index to write into pixels[]
1950      * @param stride   The number of entries in pixels[] to skip between
1951      *                 rows (must be >= bitmap's width). Can be negative.
1952      * @param x        The x coordinate of the first pixel to read from
1953      *                 the bitmap
1954      * @param y        The y coordinate of the first pixel to read from
1955      *                 the bitmap
1956      * @param width    The number of pixels to read from each row
1957      * @param height   The number of rows to read
1958      *
1959      * @throws IllegalArgumentException if x, y, width, height exceed the
1960      *         bounds of the bitmap, or if abs(stride) < width.
1961      * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
1962      *         to receive the specified number of pixels.
1963      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
1964      */
getPixels(@olorInt int[] pixels, int offset, int stride, int x, int y, int width, int height)1965     public void getPixels(@ColorInt int[] pixels, int offset, int stride,
1966                           int x, int y, int width, int height) {
1967         checkRecycled("Can't call getPixels() on a recycled bitmap");
1968         checkHardware("unable to getPixels(), "
1969                 + "pixel access is not supported on Config#HARDWARE bitmaps");
1970         if (width == 0 || height == 0) {
1971             return; // nothing to do
1972         }
1973         checkPixelsAccess(x, y, width, height, offset, stride, pixels);
1974         nativeGetPixels(mNativePtr, pixels, offset, stride,
1975                         x, y, width, height);
1976     }
1977 
1978     /**
1979      * Shared code to check for illegal arguments passed to getPixel()
1980      * or setPixel()
1981      *
1982      * @param x x coordinate of the pixel
1983      * @param y y coordinate of the pixel
1984      */
checkPixelAccess(int x, int y)1985     private void checkPixelAccess(int x, int y) {
1986         checkXYSign(x, y);
1987         if (x >= getWidth()) {
1988             throw new IllegalArgumentException("x must be < bitmap.width()");
1989         }
1990         if (y >= getHeight()) {
1991             throw new IllegalArgumentException("y must be < bitmap.height()");
1992         }
1993     }
1994 
1995     /**
1996      * Shared code to check for illegal arguments passed to getPixels()
1997      * or setPixels()
1998      *
1999      * @param x left edge of the area of pixels to access
2000      * @param y top edge of the area of pixels to access
2001      * @param width width of the area of pixels to access
2002      * @param height height of the area of pixels to access
2003      * @param offset offset into pixels[] array
2004      * @param stride number of elements in pixels[] between each logical row
2005      * @param pixels array to hold the area of pixels being accessed
2006     */
checkPixelsAccess(int x, int y, int width, int height, int offset, int stride, int pixels[])2007     private void checkPixelsAccess(int x, int y, int width, int height,
2008                                    int offset, int stride, int pixels[]) {
2009         checkXYSign(x, y);
2010         if (width < 0) {
2011             throw new IllegalArgumentException("width must be >= 0");
2012         }
2013         if (height < 0) {
2014             throw new IllegalArgumentException("height must be >= 0");
2015         }
2016         if (x + width > getWidth()) {
2017             throw new IllegalArgumentException(
2018                     "x + width must be <= bitmap.width()");
2019         }
2020         if (y + height > getHeight()) {
2021             throw new IllegalArgumentException(
2022                     "y + height must be <= bitmap.height()");
2023         }
2024         if (Math.abs(stride) < width) {
2025             throw new IllegalArgumentException("abs(stride) must be >= width");
2026         }
2027         int lastScanline = offset + (height - 1) * stride;
2028         int length = pixels.length;
2029         if (offset < 0 || (offset + width > length)
2030                 || lastScanline < 0
2031                 || (lastScanline + width > length)) {
2032             throw new ArrayIndexOutOfBoundsException();
2033         }
2034     }
2035 
2036     /**
2037      * <p>Write the specified {@link Color} into the bitmap (assuming it is
2038      * mutable) at the x,y coordinate. The color must be a
2039      * non-premultiplied ARGB value in the {@link ColorSpace.Named#SRGB sRGB}
2040      * color space.</p>
2041      *
2042      * @param x     The x coordinate of the pixel to replace (0...width-1)
2043      * @param y     The y coordinate of the pixel to replace (0...height-1)
2044      * @param color The ARGB color to write into the bitmap
2045      *
2046      * @throws IllegalStateException if the bitmap is not mutable
2047      * @throws IllegalArgumentException if x, y are outside of the bitmap's
2048      *         bounds.
2049      */
setPixel(int x, int y, @ColorInt int color)2050     public void setPixel(int x, int y, @ColorInt int color) {
2051         checkRecycled("Can't call setPixel() on a recycled bitmap");
2052         if (!isMutable()) {
2053             throw new IllegalStateException();
2054         }
2055         checkPixelAccess(x, y);
2056         nativeSetPixel(mNativePtr, x, y, color);
2057     }
2058 
2059     /**
2060      * <p>Replace pixels in the bitmap with the colors in the array. Each element
2061      * in the array is a packed int representing a non-premultiplied ARGB
2062      * {@link Color} in the {@link ColorSpace.Named#SRGB sRGB} color space.</p>
2063      *
2064      * @param pixels   The colors to write to the bitmap
2065      * @param offset   The index of the first color to read from pixels[]
2066      * @param stride   The number of colors in pixels[] to skip between rows.
2067      *                 Normally this value will be the same as the width of
2068      *                 the bitmap, but it can be larger (or negative).
2069      * @param x        The x coordinate of the first pixel to write to in
2070      *                 the bitmap.
2071      * @param y        The y coordinate of the first pixel to write to in
2072      *                 the bitmap.
2073      * @param width    The number of colors to copy from pixels[] per row
2074      * @param height   The number of rows to write to the bitmap
2075      *
2076      * @throws IllegalStateException if the bitmap is not mutable
2077      * @throws IllegalArgumentException if x, y, width, height are outside of
2078      *         the bitmap's bounds.
2079      * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
2080      *         to receive the specified number of pixels.
2081      */
setPixels(@olorInt int[] pixels, int offset, int stride, int x, int y, int width, int height)2082     public void setPixels(@ColorInt int[] pixels, int offset, int stride,
2083             int x, int y, int width, int height) {
2084         checkRecycled("Can't call setPixels() on a recycled bitmap");
2085         if (!isMutable()) {
2086             throw new IllegalStateException();
2087         }
2088         if (width == 0 || height == 0) {
2089             return; // nothing to do
2090         }
2091         checkPixelsAccess(x, y, width, height, offset, stride, pixels);
2092         nativeSetPixels(mNativePtr, pixels, offset, stride,
2093                         x, y, width, height);
2094     }
2095 
2096     public static final @android.annotation.NonNull Parcelable.Creator<Bitmap> CREATOR
2097             = new Parcelable.Creator<Bitmap>() {
2098         /**
2099          * Rebuilds a bitmap previously stored with writeToParcel().
2100          *
2101          * @param p    Parcel object to read the bitmap from
2102          * @return a new bitmap created from the data in the parcel
2103          */
2104         public Bitmap createFromParcel(Parcel p) {
2105             Bitmap bm = nativeCreateFromParcel(p);
2106             if (bm == null) {
2107                 throw new RuntimeException("Failed to unparcel Bitmap");
2108             }
2109             return bm;
2110         }
2111         public Bitmap[] newArray(int size) {
2112             return new Bitmap[size];
2113         }
2114     };
2115 
2116     /**
2117      * No special parcel contents.
2118      */
describeContents()2119     public int describeContents() {
2120         return 0;
2121     }
2122 
2123     /**
2124      * Write the bitmap and its pixels to the parcel. The bitmap can be
2125      * rebuilt from the parcel by calling CREATOR.createFromParcel().
2126      *
2127      * If this bitmap is {@link Config#HARDWARE}, it may be unparceled with a different pixel
2128      * format (e.g. 565, 8888), but the content will be preserved to the best quality permitted
2129      * by the final pixel format
2130      * @param p    Parcel object to write the bitmap data into
2131      */
writeToParcel(Parcel p, int flags)2132     public void writeToParcel(Parcel p, int flags) {
2133         checkRecycled("Can't parcel a recycled bitmap");
2134         noteHardwareBitmapSlowCall();
2135         if (!nativeWriteToParcel(mNativePtr, mDensity, p)) {
2136             throw new RuntimeException("native writeToParcel failed");
2137         }
2138     }
2139 
2140     /**
2141      * Returns a new bitmap that captures the alpha values of the original.
2142      * This may be drawn with Canvas.drawBitmap(), where the color(s) will be
2143      * taken from the paint that is passed to the draw call.
2144      *
2145      * @return new bitmap containing the alpha channel of the original bitmap.
2146      */
2147     @CheckResult
extractAlpha()2148     public Bitmap extractAlpha() {
2149         return extractAlpha(null, null);
2150     }
2151 
2152     /**
2153      * Returns a new bitmap that captures the alpha values of the original.
2154      * These values may be affected by the optional Paint parameter, which
2155      * can contain its own alpha, and may also contain a MaskFilter which
2156      * could change the actual dimensions of the resulting bitmap (e.g.
2157      * a blur maskfilter might enlarge the resulting bitmap). If offsetXY
2158      * is not null, it returns the amount to offset the returned bitmap so
2159      * that it will logically align with the original. For example, if the
2160      * paint contains a blur of radius 2, then offsetXY[] would contains
2161      * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then
2162      * drawing the original would result in the blur visually aligning with
2163      * the original.
2164      *
2165      * <p>The initial density of the returned bitmap is the same as the original's.
2166      *
2167      * @param paint Optional paint used to modify the alpha values in the
2168      *              resulting bitmap. Pass null for default behavior.
2169      * @param offsetXY Optional array that returns the X (index 0) and Y
2170      *                 (index 1) offset needed to position the returned bitmap
2171      *                 so that it visually lines up with the original.
2172      * @return new bitmap containing the (optionally modified by paint) alpha
2173      *         channel of the original bitmap. This may be drawn with
2174      *         Canvas.drawBitmap(), where the color(s) will be taken from the
2175      *         paint that is passed to the draw call.
2176      */
2177     @CheckResult
extractAlpha(Paint paint, int[] offsetXY)2178     public Bitmap extractAlpha(Paint paint, int[] offsetXY) {
2179         checkRecycled("Can't extractAlpha on a recycled bitmap");
2180         long nativePaint = paint != null ? paint.getNativeInstance() : 0;
2181         noteHardwareBitmapSlowCall();
2182         Bitmap bm = nativeExtractAlpha(mNativePtr, nativePaint, offsetXY);
2183         if (bm == null) {
2184             throw new RuntimeException("Failed to extractAlpha on Bitmap");
2185         }
2186         bm.mDensity = mDensity;
2187         return bm;
2188     }
2189 
2190     /**
2191      *  Given another bitmap, return true if it has the same dimensions, config,
2192      *  and pixel data as this bitmap. If any of those differ, return false.
2193      *  If other is null, return false.
2194      */
sameAs(Bitmap other)2195     public boolean sameAs(Bitmap other) {
2196         checkRecycled("Can't call sameAs on a recycled bitmap!");
2197         noteHardwareBitmapSlowCall();
2198         if (this == other) return true;
2199         if (other == null) return false;
2200         other.noteHardwareBitmapSlowCall();
2201         if (other.isRecycled()) {
2202             throw new IllegalArgumentException("Can't compare to a recycled bitmap!");
2203         }
2204         return nativeSameAs(mNativePtr, other.mNativePtr);
2205     }
2206 
2207     /**
2208      * Builds caches associated with the bitmap that are used for drawing it.
2209      *
2210      * <p>Starting in {@link android.os.Build.VERSION_CODES#N}, this call initiates an asynchronous
2211      * upload to the GPU on RenderThread, if the Bitmap is not already uploaded. With Hardware
2212      * Acceleration, Bitmaps must be uploaded to the GPU in order to be rendered. This is done by
2213      * default the first time a Bitmap is drawn, but the process can take several milliseconds,
2214      * depending on the size of the Bitmap. Each time a Bitmap is modified and drawn again, it must
2215      * be re-uploaded.</p>
2216      *
2217      * <p>Calling this method in advance can save time in the first frame it's used. For example, it
2218      * is recommended to call this on an image decoding worker thread when a decoded Bitmap is about
2219      * to be displayed. It is recommended to make any pre-draw modifications to the Bitmap before
2220      * calling this method, so the cached, uploaded copy may be reused without re-uploading.</p>
2221      *
2222      * In {@link android.os.Build.VERSION_CODES#KITKAT} and below, for purgeable bitmaps, this call
2223      * would attempt to ensure that the pixels have been decoded.
2224      */
prepareToDraw()2225     public void prepareToDraw() {
2226         checkRecycled("Can't prepareToDraw on a recycled bitmap!");
2227         // Kick off an update/upload of the bitmap outside of the normal
2228         // draw path.
2229         nativePrepareToDraw(mNativePtr);
2230     }
2231 
2232     /**
2233      * @return {@link GraphicBuffer} which is internally used by hardware bitmap
2234      *
2235      * Note: the GraphicBuffer does *not* have an associated {@link ColorSpace}.
2236      * To render this object the same as its rendered with this Bitmap, you
2237      * should also call {@link getColorSpace}.
2238      *
2239      * @hide
2240      */
2241     @UnsupportedAppUsage
createGraphicBufferHandle()2242     public GraphicBuffer createGraphicBufferHandle() {
2243         return GraphicBuffer.createFromHardwareBuffer(getHardwareBuffer());
2244     }
2245 
2246     /**
2247      * @return {@link HardwareBuffer} which is internally used by hardware bitmap
2248      *
2249      * Note: the HardwareBuffer does *not* have an associated {@link ColorSpace}.
2250      * To render this object the same as its rendered with this Bitmap, you
2251      * should also call {@link getColorSpace}.
2252      *
2253      * @hide
2254      */
getHardwareBuffer()2255     public HardwareBuffer getHardwareBuffer() {
2256         return nativeGetHardwareBuffer(mNativePtr);
2257     }
2258 
2259     //////////// native methods
2260 
nativeCreate(int[] colors, int offset, int stride, int width, int height, int nativeConfig, boolean mutable, long nativeColorSpace)2261     private static native Bitmap nativeCreate(int[] colors, int offset,
2262                                               int stride, int width, int height,
2263                                               int nativeConfig, boolean mutable,
2264                                               long nativeColorSpace);
nativeCopy(long nativeSrcBitmap, int nativeConfig, boolean isMutable)2265     private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig,
2266                                             boolean isMutable);
nativeCopyAshmem(long nativeSrcBitmap)2267     private static native Bitmap nativeCopyAshmem(long nativeSrcBitmap);
nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig)2268     private static native Bitmap nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig);
nativeGetNativeFinalizer()2269     private static native long nativeGetNativeFinalizer();
nativeRecycle(long nativeBitmap)2270     private static native void nativeRecycle(long nativeBitmap);
2271     @UnsupportedAppUsage
nativeReconfigure(long nativeBitmap, int width, int height, int config, boolean isPremultiplied)2272     private static native void nativeReconfigure(long nativeBitmap, int width, int height,
2273                                                  int config, boolean isPremultiplied);
2274 
nativeCompress(long nativeBitmap, int format, int quality, OutputStream stream, byte[] tempStorage)2275     private static native boolean nativeCompress(long nativeBitmap, int format,
2276                                             int quality, OutputStream stream,
2277                                             byte[] tempStorage);
nativeErase(long nativeBitmap, int color)2278     private static native void nativeErase(long nativeBitmap, int color);
nativeErase(long nativeBitmap, long colorSpacePtr, long color)2279     private static native void nativeErase(long nativeBitmap, long colorSpacePtr, long color);
nativeRowBytes(long nativeBitmap)2280     private static native int nativeRowBytes(long nativeBitmap);
nativeConfig(long nativeBitmap)2281     private static native int nativeConfig(long nativeBitmap);
2282 
nativeGetPixel(long nativeBitmap, int x, int y)2283     private static native int nativeGetPixel(long nativeBitmap, int x, int y);
nativeGetColor(long nativeBitmap, int x, int y)2284     private static native long nativeGetColor(long nativeBitmap, int x, int y);
nativeGetPixels(long nativeBitmap, int[] pixels, int offset, int stride, int x, int y, int width, int height)2285     private static native void nativeGetPixels(long nativeBitmap, int[] pixels,
2286                                                int offset, int stride, int x, int y,
2287                                                int width, int height);
2288 
nativeSetPixel(long nativeBitmap, int x, int y, int color)2289     private static native void nativeSetPixel(long nativeBitmap, int x, int y, int color);
nativeSetPixels(long nativeBitmap, int[] colors, int offset, int stride, int x, int y, int width, int height)2290     private static native void nativeSetPixels(long nativeBitmap, int[] colors,
2291                                                int offset, int stride, int x, int y,
2292                                                int width, int height);
nativeCopyPixelsToBuffer(long nativeBitmap, Buffer dst)2293     private static native void nativeCopyPixelsToBuffer(long nativeBitmap,
2294                                                         Buffer dst);
nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src)2295     private static native void nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src);
nativeGenerationId(long nativeBitmap)2296     private static native int nativeGenerationId(long nativeBitmap);
2297 
nativeCreateFromParcel(Parcel p)2298     private static native Bitmap nativeCreateFromParcel(Parcel p);
2299     // returns true on success
nativeWriteToParcel(long nativeBitmap, int density, Parcel p)2300     private static native boolean nativeWriteToParcel(long nativeBitmap,
2301                                                       int density,
2302                                                       Parcel p);
2303     // returns a new bitmap built from the native bitmap's alpha, and the paint
nativeExtractAlpha(long nativeBitmap, long nativePaint, int[] offsetXY)2304     private static native Bitmap nativeExtractAlpha(long nativeBitmap,
2305                                                     long nativePaint,
2306                                                     int[] offsetXY);
2307 
nativeHasAlpha(long nativeBitmap)2308     private static native boolean nativeHasAlpha(long nativeBitmap);
nativeIsPremultiplied(long nativeBitmap)2309     private static native boolean nativeIsPremultiplied(long nativeBitmap);
nativeSetPremultiplied(long nativeBitmap, boolean isPremul)2310     private static native void nativeSetPremultiplied(long nativeBitmap,
2311                                                       boolean isPremul);
nativeSetHasAlpha(long nativeBitmap, boolean hasAlpha, boolean requestPremul)2312     private static native void nativeSetHasAlpha(long nativeBitmap,
2313                                                  boolean hasAlpha,
2314                                                  boolean requestPremul);
nativeHasMipMap(long nativeBitmap)2315     private static native boolean nativeHasMipMap(long nativeBitmap);
nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap)2316     private static native void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap);
nativeSameAs(long nativeBitmap0, long nativeBitmap1)2317     private static native boolean nativeSameAs(long nativeBitmap0, long nativeBitmap1);
nativePrepareToDraw(long nativeBitmap)2318     private static native void nativePrepareToDraw(long nativeBitmap);
nativeGetAllocationByteCount(long nativeBitmap)2319     private static native int nativeGetAllocationByteCount(long nativeBitmap);
nativeCopyPreserveInternalConfig(long nativeBitmap)2320     private static native Bitmap nativeCopyPreserveInternalConfig(long nativeBitmap);
nativeWrapHardwareBufferBitmap(HardwareBuffer buffer, long nativeColorSpace)2321     private static native Bitmap nativeWrapHardwareBufferBitmap(HardwareBuffer buffer,
2322                                                                 long nativeColorSpace);
nativeGetHardwareBuffer(long nativeBitmap)2323     private static native HardwareBuffer nativeGetHardwareBuffer(long nativeBitmap);
nativeComputeColorSpace(long nativePtr)2324     private static native ColorSpace nativeComputeColorSpace(long nativePtr);
nativeSetColorSpace(long nativePtr, long nativeColorSpace)2325     private static native void nativeSetColorSpace(long nativePtr, long nativeColorSpace);
nativeIsSRGB(long nativePtr)2326     private static native boolean nativeIsSRGB(long nativePtr);
nativeIsSRGBLinear(long nativePtr)2327     private static native boolean nativeIsSRGBLinear(long nativePtr);
2328 
nativeSetImmutable(long nativePtr)2329     private static native void nativeSetImmutable(long nativePtr);
2330 
2331     // ---------------- @CriticalNative -------------------
2332 
2333     @CriticalNative
nativeIsImmutable(long nativePtr)2334     private static native boolean nativeIsImmutable(long nativePtr);
2335 }
2336