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         JPEG    (0),
1363         PNG     (1),
1364         WEBP    (2);
1365 
CompressFormat(int nativeInt)1366         CompressFormat(int nativeInt) {
1367             this.nativeInt = nativeInt;
1368         }
1369         final int nativeInt;
1370     }
1371 
1372     /**
1373      * Number of bytes of temp storage we use for communicating between the
1374      * native compressor and the java OutputStream.
1375      */
1376     private final static int WORKING_COMPRESS_STORAGE = 4096;
1377 
1378     /**
1379      * Write a compressed version of the bitmap to the specified outputstream.
1380      * If this returns true, the bitmap can be reconstructed by passing a
1381      * corresponding inputstream to BitmapFactory.decodeStream(). Note: not
1382      * all Formats support all bitmap configs directly, so it is possible that
1383      * the returned bitmap from BitmapFactory could be in a different bitdepth,
1384      * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque
1385      * pixels).
1386      *
1387      * @param format   The format of the compressed image
1388      * @param quality  Hint to the compressor, 0-100. 0 meaning compress for
1389      *                 small size, 100 meaning compress for max quality. Some
1390      *                 formats, like PNG which is lossless, will ignore the
1391      *                 quality setting
1392      * @param stream   The outputstream to write the compressed data.
1393      * @return true if successfully compressed to the specified stream.
1394      */
1395     @WorkerThread
compress(CompressFormat format, int quality, OutputStream stream)1396     public boolean compress(CompressFormat format, int quality, OutputStream stream) {
1397         checkRecycled("Can't compress a recycled bitmap");
1398         // do explicit check before calling the native method
1399         if (stream == null) {
1400             throw new NullPointerException();
1401         }
1402         if (quality < 0 || quality > 100) {
1403             throw new IllegalArgumentException("quality must be 0..100");
1404         }
1405         StrictMode.noteSlowCall("Compression of a bitmap is slow");
1406         Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress");
1407         boolean result = nativeCompress(mNativePtr, format.nativeInt,
1408                 quality, stream, new byte[WORKING_COMPRESS_STORAGE]);
1409         Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1410         return result;
1411     }
1412 
1413     /**
1414      * Returns true if the bitmap is marked as mutable (i.e.&nbsp;can be drawn into)
1415      */
isMutable()1416     public final boolean isMutable() {
1417         return !nativeIsImmutable(mNativePtr);
1418     }
1419 
1420     /**
1421      * Marks the Bitmap as immutable. Further modifications to this Bitmap are disallowed.
1422      * After this method is called, this Bitmap cannot be made mutable again and subsequent calls
1423      * to {@link #reconfigure(int, int, Config)}, {@link #setPixel(int, int, int)},
1424      * {@link #setPixels(int[], int, int, int, int, int, int)} and {@link #eraseColor(int)} will
1425      * fail and throw an IllegalStateException.
1426      *
1427      * @hide
1428      */
setImmutable()1429     public void setImmutable() {
1430         if (isMutable()) {
1431             nativeSetImmutable(mNativePtr);
1432         }
1433     }
1434 
1435     /**
1436      * <p>Indicates whether pixels stored in this bitmaps are stored pre-multiplied.
1437      * When a pixel is pre-multiplied, the RGB components have been multiplied by
1438      * the alpha component. For instance, if the original color is a 50%
1439      * translucent red <code>(128, 255, 0, 0)</code>, the pre-multiplied form is
1440      * <code>(128, 128, 0, 0)</code>.</p>
1441      *
1442      * <p>This method always returns false if {@link #getConfig()} is
1443      * {@link Bitmap.Config#RGB_565}.</p>
1444      *
1445      * <p>The return value is undefined if {@link #getConfig()} is
1446      * {@link Bitmap.Config#ALPHA_8}.</p>
1447      *
1448      * <p>This method only returns true if {@link #hasAlpha()} returns true.
1449      * A bitmap with no alpha channel can be used both as a pre-multiplied and
1450      * as a non pre-multiplied bitmap.</p>
1451      *
1452      * <p>Only pre-multiplied bitmaps may be drawn by the view system or
1453      * {@link Canvas}. If a non-pre-multiplied bitmap with an alpha channel is
1454      * drawn to a Canvas, a RuntimeException will be thrown.</p>
1455      *
1456      * @return true if the underlying pixels have been pre-multiplied, false
1457      *         otherwise
1458      *
1459      * @see Bitmap#setPremultiplied(boolean)
1460      * @see BitmapFactory.Options#inPremultiplied
1461      */
isPremultiplied()1462     public final boolean isPremultiplied() {
1463         if (mRecycled) {
1464             Log.w(TAG, "Called isPremultiplied() on a recycle()'d bitmap! This is undefined behavior!");
1465         }
1466         return nativeIsPremultiplied(mNativePtr);
1467     }
1468 
1469     /**
1470      * Sets whether the bitmap should treat its data as pre-multiplied.
1471      *
1472      * <p>Bitmaps are always treated as pre-multiplied by the view system and
1473      * {@link Canvas} for performance reasons. Storing un-pre-multiplied data in
1474      * a Bitmap (through {@link #setPixel}, {@link #setPixels}, or {@link
1475      * BitmapFactory.Options#inPremultiplied BitmapFactory.Options.inPremultiplied})
1476      * can lead to incorrect blending if drawn by the framework.</p>
1477      *
1478      * <p>This method will not affect the behavior of a bitmap without an alpha
1479      * channel, or if {@link #hasAlpha()} returns false.</p>
1480      *
1481      * <p>Calling {@link #createBitmap} or {@link #createScaledBitmap} with a source
1482      * Bitmap whose colors are not pre-multiplied may result in a RuntimeException,
1483      * since those functions require drawing the source, which is not supported for
1484      * un-pre-multiplied Bitmaps.</p>
1485      *
1486      * @see Bitmap#isPremultiplied()
1487      * @see BitmapFactory.Options#inPremultiplied
1488      */
setPremultiplied(boolean premultiplied)1489     public final void setPremultiplied(boolean premultiplied) {
1490         checkRecycled("setPremultiplied called on a recycled bitmap");
1491         mRequestPremultiplied = premultiplied;
1492         nativeSetPremultiplied(mNativePtr, premultiplied);
1493     }
1494 
1495     /** Returns the bitmap's width */
getWidth()1496     public final int getWidth() {
1497         if (mRecycled) {
1498             Log.w(TAG, "Called getWidth() on a recycle()'d bitmap! This is undefined behavior!");
1499         }
1500         return mWidth;
1501     }
1502 
1503     /** Returns the bitmap's height */
getHeight()1504     public final int getHeight() {
1505         if (mRecycled) {
1506             Log.w(TAG, "Called getHeight() on a recycle()'d bitmap! This is undefined behavior!");
1507         }
1508         return mHeight;
1509     }
1510 
1511     /**
1512      * Convenience for calling {@link #getScaledWidth(int)} with the target
1513      * density of the given {@link Canvas}.
1514      */
getScaledWidth(Canvas canvas)1515     public int getScaledWidth(Canvas canvas) {
1516         return scaleFromDensity(getWidth(), mDensity, canvas.mDensity);
1517     }
1518 
1519     /**
1520      * Convenience for calling {@link #getScaledHeight(int)} with the target
1521      * density of the given {@link Canvas}.
1522      */
getScaledHeight(Canvas canvas)1523     public int getScaledHeight(Canvas canvas) {
1524         return scaleFromDensity(getHeight(), mDensity, canvas.mDensity);
1525     }
1526 
1527     /**
1528      * Convenience for calling {@link #getScaledWidth(int)} with the target
1529      * density of the given {@link DisplayMetrics}.
1530      */
getScaledWidth(DisplayMetrics metrics)1531     public int getScaledWidth(DisplayMetrics metrics) {
1532         return scaleFromDensity(getWidth(), mDensity, metrics.densityDpi);
1533     }
1534 
1535     /**
1536      * Convenience for calling {@link #getScaledHeight(int)} with the target
1537      * density of the given {@link DisplayMetrics}.
1538      */
getScaledHeight(DisplayMetrics metrics)1539     public int getScaledHeight(DisplayMetrics metrics) {
1540         return scaleFromDensity(getHeight(), mDensity, metrics.densityDpi);
1541     }
1542 
1543     /**
1544      * Convenience method that returns the width of this bitmap divided
1545      * by the density scale factor.
1546      *
1547      * Returns the bitmap's width multiplied by the ratio of the target density to the bitmap's
1548      * source density
1549      *
1550      * @param targetDensity The density of the target canvas of the bitmap.
1551      * @return The scaled width of this bitmap, according to the density scale factor.
1552      */
getScaledWidth(int targetDensity)1553     public int getScaledWidth(int targetDensity) {
1554         return scaleFromDensity(getWidth(), mDensity, targetDensity);
1555     }
1556 
1557     /**
1558      * Convenience method that returns the height of this bitmap divided
1559      * by the density scale factor.
1560      *
1561      * Returns the bitmap's height multiplied by the ratio of the target density to the bitmap's
1562      * source density
1563      *
1564      * @param targetDensity The density of the target canvas of the bitmap.
1565      * @return The scaled height of this bitmap, according to the density scale factor.
1566      */
getScaledHeight(int targetDensity)1567     public int getScaledHeight(int targetDensity) {
1568         return scaleFromDensity(getHeight(), mDensity, targetDensity);
1569     }
1570 
1571     /**
1572      * @hide
1573      */
1574     @UnsupportedAppUsage
scaleFromDensity(int size, int sdensity, int tdensity)1575     static public int scaleFromDensity(int size, int sdensity, int tdensity) {
1576         if (sdensity == DENSITY_NONE || tdensity == DENSITY_NONE || sdensity == tdensity) {
1577             return size;
1578         }
1579 
1580         // Scale by tdensity / sdensity, rounding up.
1581         return ((size * tdensity) + (sdensity >> 1)) / sdensity;
1582     }
1583 
1584     /**
1585      * Return the number of bytes between rows in the bitmap's pixels. Note that
1586      * this refers to the pixels as stored natively by the bitmap. If you call
1587      * getPixels() or setPixels(), then the pixels are uniformly treated as
1588      * 32bit values, packed according to the Color class.
1589      *
1590      * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, this method
1591      * should not be used to calculate the memory usage of the bitmap. Instead,
1592      * see {@link #getAllocationByteCount()}.
1593      *
1594      * @return number of bytes between rows of the native bitmap pixels.
1595      */
getRowBytes()1596     public final int getRowBytes() {
1597         if (mRecycled) {
1598             Log.w(TAG, "Called getRowBytes() on a recycle()'d bitmap! This is undefined behavior!");
1599         }
1600         return nativeRowBytes(mNativePtr);
1601     }
1602 
1603     /**
1604      * Returns the minimum number of bytes that can be used to store this bitmap's pixels.
1605      *
1606      * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can
1607      * no longer be used to determine memory usage of a bitmap. See {@link
1608      * #getAllocationByteCount()}.</p>
1609      */
getByteCount()1610     public final int getByteCount() {
1611         if (mRecycled) {
1612             Log.w(TAG, "Called getByteCount() on a recycle()'d bitmap! "
1613                     + "This is undefined behavior!");
1614             return 0;
1615         }
1616         // int result permits bitmaps up to 46,340 x 46,340
1617         return getRowBytes() * getHeight();
1618     }
1619 
1620     /**
1621      * Returns the size of the allocated memory used to store this bitmap's pixels.
1622      *
1623      * <p>This can be larger than the result of {@link #getByteCount()} if a bitmap is reused to
1624      * decode other bitmaps of smaller size, or by manual reconfiguration. See {@link
1625      * #reconfigure(int, int, Config)}, {@link #setWidth(int)}, {@link #setHeight(int)}, {@link
1626      * #setConfig(Bitmap.Config)}, and {@link BitmapFactory.Options#inBitmap
1627      * BitmapFactory.Options.inBitmap}. If a bitmap is not modified in this way, this value will be
1628      * the same as that returned by {@link #getByteCount()}.</p>
1629      *
1630      * <p>This value will not change over the lifetime of a Bitmap.</p>
1631      *
1632      * @see #reconfigure(int, int, Config)
1633      */
getAllocationByteCount()1634     public final int getAllocationByteCount() {
1635         if (mRecycled) {
1636             Log.w(TAG, "Called getAllocationByteCount() on a recycle()'d bitmap! "
1637                     + "This is undefined behavior!");
1638             return 0;
1639         }
1640         return nativeGetAllocationByteCount(mNativePtr);
1641     }
1642 
1643     /**
1644      * If the bitmap's internal config is in one of the public formats, return
1645      * that config, otherwise return null.
1646      */
getConfig()1647     public final Config getConfig() {
1648         if (mRecycled) {
1649             Log.w(TAG, "Called getConfig() on a recycle()'d bitmap! This is undefined behavior!");
1650         }
1651         return Config.nativeToConfig(nativeConfig(mNativePtr));
1652     }
1653 
1654     /** Returns true if the bitmap's config supports per-pixel alpha, and
1655      * if the pixels may contain non-opaque alpha values. For some configs,
1656      * this is always false (e.g. RGB_565), since they do not support per-pixel
1657      * alpha. However, for configs that do, the bitmap may be flagged to be
1658      * known that all of its pixels are opaque. In this case hasAlpha() will
1659      * also return false. If a config such as ARGB_8888 is not so flagged,
1660      * it will return true by default.
1661      */
hasAlpha()1662     public final boolean hasAlpha() {
1663         if (mRecycled) {
1664             Log.w(TAG, "Called hasAlpha() on a recycle()'d bitmap! This is undefined behavior!");
1665         }
1666         return nativeHasAlpha(mNativePtr);
1667     }
1668 
1669     /**
1670      * Tell the bitmap if all of the pixels are known to be opaque (false)
1671      * or if some of the pixels may contain non-opaque alpha values (true).
1672      * Note, for some configs (e.g. RGB_565) this call is ignored, since it
1673      * does not support per-pixel alpha values.
1674      *
1675      * This is meant as a drawing hint, as in some cases a bitmap that is known
1676      * to be opaque can take a faster drawing case than one that may have
1677      * non-opaque per-pixel alpha values.
1678      */
setHasAlpha(boolean hasAlpha)1679     public void setHasAlpha(boolean hasAlpha) {
1680         checkRecycled("setHasAlpha called on a recycled bitmap");
1681         nativeSetHasAlpha(mNativePtr, hasAlpha, mRequestPremultiplied);
1682     }
1683 
1684     /**
1685      * Indicates whether the renderer responsible for drawing this
1686      * bitmap should attempt to use mipmaps when this bitmap is drawn
1687      * scaled down.
1688      *
1689      * If you know that you are going to draw this bitmap at less than
1690      * 50% of its original size, you may be able to obtain a higher
1691      * quality
1692      *
1693      * This property is only a suggestion that can be ignored by the
1694      * renderer. It is not guaranteed to have any effect.
1695      *
1696      * @return true if the renderer should attempt to use mipmaps,
1697      *         false otherwise
1698      *
1699      * @see #setHasMipMap(boolean)
1700      */
hasMipMap()1701     public final boolean hasMipMap() {
1702         if (mRecycled) {
1703             Log.w(TAG, "Called hasMipMap() on a recycle()'d bitmap! This is undefined behavior!");
1704         }
1705         return nativeHasMipMap(mNativePtr);
1706     }
1707 
1708     /**
1709      * Set a hint for the renderer responsible for drawing this bitmap
1710      * indicating that it should attempt to use mipmaps when this bitmap
1711      * is drawn scaled down.
1712      *
1713      * If you know that you are going to draw this bitmap at less than
1714      * 50% of its original size, you may be able to obtain a higher
1715      * quality by turning this property on.
1716      *
1717      * Note that if the renderer respects this hint it might have to
1718      * allocate extra memory to hold the mipmap levels for this bitmap.
1719      *
1720      * This property is only a suggestion that can be ignored by the
1721      * renderer. It is not guaranteed to have any effect.
1722      *
1723      * @param hasMipMap indicates whether the renderer should attempt
1724      *                  to use mipmaps
1725      *
1726      * @see #hasMipMap()
1727      */
setHasMipMap(boolean hasMipMap)1728     public final void setHasMipMap(boolean hasMipMap) {
1729         checkRecycled("setHasMipMap called on a recycled bitmap");
1730         nativeSetHasMipMap(mNativePtr, hasMipMap);
1731     }
1732 
1733     /**
1734      * Returns the color space associated with this bitmap. If the color
1735      * space is unknown, this method returns null.
1736      */
1737     @Nullable
getColorSpace()1738     public final ColorSpace getColorSpace() {
1739         checkRecycled("getColorSpace called on a recycled bitmap");
1740         if (mColorSpace == null) {
1741             mColorSpace = nativeComputeColorSpace(mNativePtr);
1742         }
1743         return mColorSpace;
1744     }
1745 
1746     /**
1747      * <p>Modifies the bitmap to have the specified {@link ColorSpace}, without
1748      * affecting the underlying allocation backing the bitmap.</p>
1749      *
1750      * <p>This affects how the framework will interpret the color at each pixel. A bitmap
1751      * with {@link Config#ALPHA_8} never has a color space, since a color space does not
1752      * affect the alpha channel. Other {@code Config}s must always have a non-null
1753      * {@code ColorSpace}.</p>
1754      *
1755      * @throws IllegalArgumentException If the specified color space is {@code null}, not
1756      *         {@link ColorSpace.Model#RGB RGB}, has a transfer function that is not an
1757      *         {@link ColorSpace.Rgb.TransferParameters ICC parametric curve}, or whose
1758      *         components min/max values reduce the numerical range compared to the
1759      *         previously assigned color space.
1760      *
1761      * @throws IllegalArgumentException If the {@code Config} (returned by {@link #getConfig()})
1762      *         is {@link Config#ALPHA_8}.
1763      *
1764      * @param colorSpace to assign to the bitmap
1765      */
setColorSpace(@onNull ColorSpace colorSpace)1766     public void setColorSpace(@NonNull ColorSpace colorSpace) {
1767         checkRecycled("setColorSpace called on a recycled bitmap");
1768         if (colorSpace == null) {
1769             throw new IllegalArgumentException("The colorSpace cannot be set to null");
1770         }
1771 
1772         if (getConfig() == Config.ALPHA_8) {
1773             throw new IllegalArgumentException("Cannot set a ColorSpace on ALPHA_8");
1774         }
1775 
1776         // Keep track of the old ColorSpace for comparison, and so we can reset it in case of an
1777         // Exception.
1778         final ColorSpace oldColorSpace = getColorSpace();
1779         nativeSetColorSpace(mNativePtr, colorSpace.getNativeInstance());
1780 
1781         // This will update mColorSpace. It may not be the same as |colorSpace|, e.g. if we
1782         // corrected it because the Bitmap is F16.
1783         mColorSpace = null;
1784         final ColorSpace newColorSpace = getColorSpace();
1785 
1786         try {
1787             if (oldColorSpace.getComponentCount() != newColorSpace.getComponentCount()) {
1788                 throw new IllegalArgumentException("The new ColorSpace must have the same "
1789                         + "component count as the current ColorSpace");
1790             } else {
1791                 for (int i = 0; i < oldColorSpace.getComponentCount(); i++) {
1792                     if (oldColorSpace.getMinValue(i) < newColorSpace.getMinValue(i)) {
1793                         throw new IllegalArgumentException("The new ColorSpace cannot increase the "
1794                                 + "minimum value for any of the components compared to the current "
1795                                 + "ColorSpace. To perform this type of conversion create a new "
1796                                 + "Bitmap in the desired ColorSpace and draw this Bitmap into it.");
1797                     }
1798                     if (oldColorSpace.getMaxValue(i) > newColorSpace.getMaxValue(i)) {
1799                         throw new IllegalArgumentException("The new ColorSpace cannot decrease the "
1800                                 + "maximum value for any of the components compared to the current "
1801                                 + "ColorSpace/ To perform this type of conversion create a new "
1802                                 + "Bitmap in the desired ColorSpace and draw this Bitmap into it.");
1803                     }
1804                 }
1805             }
1806         } catch (IllegalArgumentException e) {
1807             // Undo the change to the ColorSpace.
1808             mColorSpace = oldColorSpace;
1809             nativeSetColorSpace(mNativePtr, mColorSpace.getNativeInstance());
1810             throw e;
1811         }
1812     }
1813 
1814     /**
1815      * Fills the bitmap's pixels with the specified {@link Color}.
1816      *
1817      * @throws IllegalStateException if the bitmap is not mutable.
1818      */
eraseColor(@olorInt int c)1819     public void eraseColor(@ColorInt int c) {
1820         checkRecycled("Can't erase a recycled bitmap");
1821         if (!isMutable()) {
1822             throw new IllegalStateException("cannot erase immutable bitmaps");
1823         }
1824         nativeErase(mNativePtr, c);
1825     }
1826 
1827     /**
1828      * Fills the bitmap's pixels with the specified {@code ColorLong}.
1829      *
1830      * @param color The color to fill as packed by the {@link Color} class.
1831      * @throws IllegalStateException if the bitmap is not mutable.
1832      * @throws IllegalArgumentException if the color space encoded in the
1833      *                                  {@code ColorLong} is invalid or unknown.
1834      *
1835      */
eraseColor(@olorLong long color)1836     public void eraseColor(@ColorLong long color) {
1837         checkRecycled("Can't erase a recycled bitmap");
1838         if (!isMutable()) {
1839             throw new IllegalStateException("cannot erase immutable bitmaps");
1840         }
1841 
1842         ColorSpace cs = Color.colorSpace(color);
1843         nativeErase(mNativePtr, cs.getNativeInstance(), color);
1844     }
1845 
1846     /**
1847      * Returns the {@link Color} at the specified location. Throws an exception
1848      * if x or y are out of bounds (negative or >= to the width or height
1849      * respectively). The returned color is a non-premultiplied ARGB value in
1850      * the {@link ColorSpace.Named#SRGB sRGB} color space.
1851      *
1852      * @param x    The x coordinate (0...width-1) of the pixel to return
1853      * @param y    The y coordinate (0...height-1) of the pixel to return
1854      * @return     The argb {@link Color} at the specified coordinate
1855      * @throws IllegalArgumentException if x, y exceed the bitmap's bounds
1856      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
1857      */
1858     @ColorInt
getPixel(int x, int y)1859     public int getPixel(int x, int y) {
1860         checkRecycled("Can't call getPixel() on a recycled bitmap");
1861         checkHardware("unable to getPixel(), "
1862                 + "pixel access is not supported on Config#HARDWARE bitmaps");
1863         checkPixelAccess(x, y);
1864         return nativeGetPixel(mNativePtr, x, y);
1865     }
1866 
clamp(float value, @NonNull ColorSpace cs, int index)1867     private static float clamp(float value, @NonNull ColorSpace cs, int index) {
1868         return Math.max(Math.min(value, cs.getMaxValue(index)), cs.getMinValue(index));
1869     }
1870 
1871     /**
1872      * Returns the {@link Color} at the specified location. Throws an exception
1873      * if x or y are out of bounds (negative or >= to the width or height
1874      * respectively).
1875      *
1876      * @param x    The x coordinate (0...width-1) of the pixel to return
1877      * @param y    The y coordinate (0...height-1) of the pixel to return
1878      * @return     The {@link Color} at the specified coordinate
1879      * @throws IllegalArgumentException if x, y exceed the bitmap's bounds
1880      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
1881      *
1882      */
1883     @NonNull
getColor(int x, int y)1884     public Color getColor(int x, int y) {
1885         checkRecycled("Can't call getColor() on a recycled bitmap");
1886         checkHardware("unable to getColor(), "
1887                 + "pixel access is not supported on Config#HARDWARE bitmaps");
1888         checkPixelAccess(x, y);
1889 
1890         final ColorSpace cs = getColorSpace();
1891         if (cs.equals(ColorSpace.get(ColorSpace.Named.SRGB))) {
1892             return Color.valueOf(nativeGetPixel(mNativePtr, x, y));
1893         }
1894         // The returned value is in kRGBA_F16_SkColorType, which is packed as
1895         // four half-floats, r,g,b,a.
1896         long rgba = nativeGetColor(mNativePtr, x, y);
1897         float r = Half.toFloat((short) ((rgba >>  0) & 0xffff));
1898         float g = Half.toFloat((short) ((rgba >> 16) & 0xffff));
1899         float b = Half.toFloat((short) ((rgba >> 32) & 0xffff));
1900         float a = Half.toFloat((short) ((rgba >> 48) & 0xffff));
1901 
1902         // Skia may draw outside of the numerical range of the colorSpace.
1903         // Clamp to get an expected value.
1904         return Color.valueOf(clamp(r, cs, 0), clamp(g, cs, 1), clamp(b, cs, 2), a, cs);
1905     }
1906 
1907     /**
1908      * Returns in pixels[] a copy of the data in the bitmap. Each value is
1909      * a packed int representing a {@link Color}. The stride parameter allows
1910      * the caller to allow for gaps in the returned pixels array between
1911      * rows. For normal packed results, just pass width for the stride value.
1912      * The returned colors are non-premultiplied ARGB values in the
1913      * {@link ColorSpace.Named#SRGB sRGB} color space.
1914      *
1915      * @param pixels   The array to receive the bitmap's colors
1916      * @param offset   The first index to write into pixels[]
1917      * @param stride   The number of entries in pixels[] to skip between
1918      *                 rows (must be >= bitmap's width). Can be negative.
1919      * @param x        The x coordinate of the first pixel to read from
1920      *                 the bitmap
1921      * @param y        The y coordinate of the first pixel to read from
1922      *                 the bitmap
1923      * @param width    The number of pixels to read from each row
1924      * @param height   The number of rows to read
1925      *
1926      * @throws IllegalArgumentException if x, y, width, height exceed the
1927      *         bounds of the bitmap, or if abs(stride) < width.
1928      * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
1929      *         to receive the specified number of pixels.
1930      * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
1931      */
getPixels(@olorInt int[] pixels, int offset, int stride, int x, int y, int width, int height)1932     public void getPixels(@ColorInt int[] pixels, int offset, int stride,
1933                           int x, int y, int width, int height) {
1934         checkRecycled("Can't call getPixels() on a recycled bitmap");
1935         checkHardware("unable to getPixels(), "
1936                 + "pixel access is not supported on Config#HARDWARE bitmaps");
1937         if (width == 0 || height == 0) {
1938             return; // nothing to do
1939         }
1940         checkPixelsAccess(x, y, width, height, offset, stride, pixels);
1941         nativeGetPixels(mNativePtr, pixels, offset, stride,
1942                         x, y, width, height);
1943     }
1944 
1945     /**
1946      * Shared code to check for illegal arguments passed to getPixel()
1947      * or setPixel()
1948      *
1949      * @param x x coordinate of the pixel
1950      * @param y y coordinate of the pixel
1951      */
checkPixelAccess(int x, int y)1952     private void checkPixelAccess(int x, int y) {
1953         checkXYSign(x, y);
1954         if (x >= getWidth()) {
1955             throw new IllegalArgumentException("x must be < bitmap.width()");
1956         }
1957         if (y >= getHeight()) {
1958             throw new IllegalArgumentException("y must be < bitmap.height()");
1959         }
1960     }
1961 
1962     /**
1963      * Shared code to check for illegal arguments passed to getPixels()
1964      * or setPixels()
1965      *
1966      * @param x left edge of the area of pixels to access
1967      * @param y top edge of the area of pixels to access
1968      * @param width width of the area of pixels to access
1969      * @param height height of the area of pixels to access
1970      * @param offset offset into pixels[] array
1971      * @param stride number of elements in pixels[] between each logical row
1972      * @param pixels array to hold the area of pixels being accessed
1973     */
checkPixelsAccess(int x, int y, int width, int height, int offset, int stride, int pixels[])1974     private void checkPixelsAccess(int x, int y, int width, int height,
1975                                    int offset, int stride, int pixels[]) {
1976         checkXYSign(x, y);
1977         if (width < 0) {
1978             throw new IllegalArgumentException("width must be >= 0");
1979         }
1980         if (height < 0) {
1981             throw new IllegalArgumentException("height must be >= 0");
1982         }
1983         if (x + width > getWidth()) {
1984             throw new IllegalArgumentException(
1985                     "x + width must be <= bitmap.width()");
1986         }
1987         if (y + height > getHeight()) {
1988             throw new IllegalArgumentException(
1989                     "y + height must be <= bitmap.height()");
1990         }
1991         if (Math.abs(stride) < width) {
1992             throw new IllegalArgumentException("abs(stride) must be >= width");
1993         }
1994         int lastScanline = offset + (height - 1) * stride;
1995         int length = pixels.length;
1996         if (offset < 0 || (offset + width > length)
1997                 || lastScanline < 0
1998                 || (lastScanline + width > length)) {
1999             throw new ArrayIndexOutOfBoundsException();
2000         }
2001     }
2002 
2003     /**
2004      * <p>Write the specified {@link Color} into the bitmap (assuming it is
2005      * mutable) at the x,y coordinate. The color must be a
2006      * non-premultiplied ARGB value in the {@link ColorSpace.Named#SRGB sRGB}
2007      * color space.</p>
2008      *
2009      * @param x     The x coordinate of the pixel to replace (0...width-1)
2010      * @param y     The y coordinate of the pixel to replace (0...height-1)
2011      * @param color The ARGB color to write into the bitmap
2012      *
2013      * @throws IllegalStateException if the bitmap is not mutable
2014      * @throws IllegalArgumentException if x, y are outside of the bitmap's
2015      *         bounds.
2016      */
setPixel(int x, int y, @ColorInt int color)2017     public void setPixel(int x, int y, @ColorInt int color) {
2018         checkRecycled("Can't call setPixel() on a recycled bitmap");
2019         if (!isMutable()) {
2020             throw new IllegalStateException();
2021         }
2022         checkPixelAccess(x, y);
2023         nativeSetPixel(mNativePtr, x, y, color);
2024     }
2025 
2026     /**
2027      * <p>Replace pixels in the bitmap with the colors in the array. Each element
2028      * in the array is a packed int representing a non-premultiplied ARGB
2029      * {@link Color} in the {@link ColorSpace.Named#SRGB sRGB} color space.</p>
2030      *
2031      * @param pixels   The colors to write to the bitmap
2032      * @param offset   The index of the first color to read from pixels[]
2033      * @param stride   The number of colors in pixels[] to skip between rows.
2034      *                 Normally this value will be the same as the width of
2035      *                 the bitmap, but it can be larger (or negative).
2036      * @param x        The x coordinate of the first pixel to write to in
2037      *                 the bitmap.
2038      * @param y        The y coordinate of the first pixel to write to in
2039      *                 the bitmap.
2040      * @param width    The number of colors to copy from pixels[] per row
2041      * @param height   The number of rows to write to the bitmap
2042      *
2043      * @throws IllegalStateException if the bitmap is not mutable
2044      * @throws IllegalArgumentException if x, y, width, height are outside of
2045      *         the bitmap's bounds.
2046      * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
2047      *         to receive the specified number of pixels.
2048      */
setPixels(@olorInt int[] pixels, int offset, int stride, int x, int y, int width, int height)2049     public void setPixels(@ColorInt int[] pixels, int offset, int stride,
2050             int x, int y, int width, int height) {
2051         checkRecycled("Can't call setPixels() on a recycled bitmap");
2052         if (!isMutable()) {
2053             throw new IllegalStateException();
2054         }
2055         if (width == 0 || height == 0) {
2056             return; // nothing to do
2057         }
2058         checkPixelsAccess(x, y, width, height, offset, stride, pixels);
2059         nativeSetPixels(mNativePtr, pixels, offset, stride,
2060                         x, y, width, height);
2061     }
2062 
2063     public static final @android.annotation.NonNull Parcelable.Creator<Bitmap> CREATOR
2064             = new Parcelable.Creator<Bitmap>() {
2065         /**
2066          * Rebuilds a bitmap previously stored with writeToParcel().
2067          *
2068          * @param p    Parcel object to read the bitmap from
2069          * @return a new bitmap created from the data in the parcel
2070          */
2071         public Bitmap createFromParcel(Parcel p) {
2072             Bitmap bm = nativeCreateFromParcel(p);
2073             if (bm == null) {
2074                 throw new RuntimeException("Failed to unparcel Bitmap");
2075             }
2076             return bm;
2077         }
2078         public Bitmap[] newArray(int size) {
2079             return new Bitmap[size];
2080         }
2081     };
2082 
2083     /**
2084      * No special parcel contents.
2085      */
describeContents()2086     public int describeContents() {
2087         return 0;
2088     }
2089 
2090     /**
2091      * Write the bitmap and its pixels to the parcel. The bitmap can be
2092      * rebuilt from the parcel by calling CREATOR.createFromParcel().
2093      *
2094      * If this bitmap is {@link Config#HARDWARE}, it may be unparceled with a different pixel
2095      * format (e.g. 565, 8888), but the content will be preserved to the best quality permitted
2096      * by the final pixel format
2097      * @param p    Parcel object to write the bitmap data into
2098      */
writeToParcel(Parcel p, int flags)2099     public void writeToParcel(Parcel p, int flags) {
2100         checkRecycled("Can't parcel a recycled bitmap");
2101         noteHardwareBitmapSlowCall();
2102         if (!nativeWriteToParcel(mNativePtr, isMutable(), mDensity, p)) {
2103             throw new RuntimeException("native writeToParcel failed");
2104         }
2105     }
2106 
2107     /**
2108      * Returns a new bitmap that captures the alpha values of the original.
2109      * This may be drawn with Canvas.drawBitmap(), where the color(s) will be
2110      * taken from the paint that is passed to the draw call.
2111      *
2112      * @return new bitmap containing the alpha channel of the original bitmap.
2113      */
2114     @CheckResult
extractAlpha()2115     public Bitmap extractAlpha() {
2116         return extractAlpha(null, null);
2117     }
2118 
2119     /**
2120      * Returns a new bitmap that captures the alpha values of the original.
2121      * These values may be affected by the optional Paint parameter, which
2122      * can contain its own alpha, and may also contain a MaskFilter which
2123      * could change the actual dimensions of the resulting bitmap (e.g.
2124      * a blur maskfilter might enlarge the resulting bitmap). If offsetXY
2125      * is not null, it returns the amount to offset the returned bitmap so
2126      * that it will logically align with the original. For example, if the
2127      * paint contains a blur of radius 2, then offsetXY[] would contains
2128      * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then
2129      * drawing the original would result in the blur visually aligning with
2130      * the original.
2131      *
2132      * <p>The initial density of the returned bitmap is the same as the original's.
2133      *
2134      * @param paint Optional paint used to modify the alpha values in the
2135      *              resulting bitmap. Pass null for default behavior.
2136      * @param offsetXY Optional array that returns the X (index 0) and Y
2137      *                 (index 1) offset needed to position the returned bitmap
2138      *                 so that it visually lines up with the original.
2139      * @return new bitmap containing the (optionally modified by paint) alpha
2140      *         channel of the original bitmap. This may be drawn with
2141      *         Canvas.drawBitmap(), where the color(s) will be taken from the
2142      *         paint that is passed to the draw call.
2143      */
2144     @CheckResult
extractAlpha(Paint paint, int[] offsetXY)2145     public Bitmap extractAlpha(Paint paint, int[] offsetXY) {
2146         checkRecycled("Can't extractAlpha on a recycled bitmap");
2147         long nativePaint = paint != null ? paint.getNativeInstance() : 0;
2148         noteHardwareBitmapSlowCall();
2149         Bitmap bm = nativeExtractAlpha(mNativePtr, nativePaint, offsetXY);
2150         if (bm == null) {
2151             throw new RuntimeException("Failed to extractAlpha on Bitmap");
2152         }
2153         bm.mDensity = mDensity;
2154         return bm;
2155     }
2156 
2157     /**
2158      *  Given another bitmap, return true if it has the same dimensions, config,
2159      *  and pixel data as this bitmap. If any of those differ, return false.
2160      *  If other is null, return false.
2161      */
sameAs(Bitmap other)2162     public boolean sameAs(Bitmap other) {
2163         checkRecycled("Can't call sameAs on a recycled bitmap!");
2164         noteHardwareBitmapSlowCall();
2165         if (this == other) return true;
2166         if (other == null) return false;
2167         other.noteHardwareBitmapSlowCall();
2168         if (other.isRecycled()) {
2169             throw new IllegalArgumentException("Can't compare to a recycled bitmap!");
2170         }
2171         return nativeSameAs(mNativePtr, other.mNativePtr);
2172     }
2173 
2174     /**
2175      * Builds caches associated with the bitmap that are used for drawing it.
2176      *
2177      * <p>Starting in {@link android.os.Build.VERSION_CODES#N}, this call initiates an asynchronous
2178      * upload to the GPU on RenderThread, if the Bitmap is not already uploaded. With Hardware
2179      * Acceleration, Bitmaps must be uploaded to the GPU in order to be rendered. This is done by
2180      * default the first time a Bitmap is drawn, but the process can take several milliseconds,
2181      * depending on the size of the Bitmap. Each time a Bitmap is modified and drawn again, it must
2182      * be re-uploaded.</p>
2183      *
2184      * <p>Calling this method in advance can save time in the first frame it's used. For example, it
2185      * is recommended to call this on an image decoding worker thread when a decoded Bitmap is about
2186      * to be displayed. It is recommended to make any pre-draw modifications to the Bitmap before
2187      * calling this method, so the cached, uploaded copy may be reused without re-uploading.</p>
2188      *
2189      * In {@link android.os.Build.VERSION_CODES#KITKAT} and below, for purgeable bitmaps, this call
2190      * would attempt to ensure that the pixels have been decoded.
2191      */
prepareToDraw()2192     public void prepareToDraw() {
2193         checkRecycled("Can't prepareToDraw on a recycled bitmap!");
2194         // Kick off an update/upload of the bitmap outside of the normal
2195         // draw path.
2196         nativePrepareToDraw(mNativePtr);
2197     }
2198 
2199     /**
2200      * @return {@link GraphicBuffer} which is internally used by hardware bitmap
2201      *
2202      * Note: the GraphicBuffer does *not* have an associated {@link ColorSpace}.
2203      * To render this object the same as its rendered with this Bitmap, you
2204      * should also call {@link getColorSpace}.
2205      *
2206      * @hide
2207      */
2208     @UnsupportedAppUsage
createGraphicBufferHandle()2209     public GraphicBuffer createGraphicBufferHandle() {
2210         return nativeCreateGraphicBufferHandle(mNativePtr);
2211     }
2212 
2213     //////////// native methods
2214 
nativeCreate(int[] colors, int offset, int stride, int width, int height, int nativeConfig, boolean mutable, long nativeColorSpace)2215     private static native Bitmap nativeCreate(int[] colors, int offset,
2216                                               int stride, int width, int height,
2217                                               int nativeConfig, boolean mutable,
2218                                               long nativeColorSpace);
nativeCopy(long nativeSrcBitmap, int nativeConfig, boolean isMutable)2219     private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig,
2220                                             boolean isMutable);
nativeCopyAshmem(long nativeSrcBitmap)2221     private static native Bitmap nativeCopyAshmem(long nativeSrcBitmap);
nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig)2222     private static native Bitmap nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig);
nativeGetNativeFinalizer()2223     private static native long nativeGetNativeFinalizer();
nativeRecycle(long nativeBitmap)2224     private static native void nativeRecycle(long nativeBitmap);
2225     @UnsupportedAppUsage
nativeReconfigure(long nativeBitmap, int width, int height, int config, boolean isPremultiplied)2226     private static native void nativeReconfigure(long nativeBitmap, int width, int height,
2227                                                  int config, boolean isPremultiplied);
2228 
nativeCompress(long nativeBitmap, int format, int quality, OutputStream stream, byte[] tempStorage)2229     private static native boolean nativeCompress(long nativeBitmap, int format,
2230                                             int quality, OutputStream stream,
2231                                             byte[] tempStorage);
nativeErase(long nativeBitmap, int color)2232     private static native void nativeErase(long nativeBitmap, int color);
nativeErase(long nativeBitmap, long colorSpacePtr, long color)2233     private static native void nativeErase(long nativeBitmap, long colorSpacePtr, long color);
nativeRowBytes(long nativeBitmap)2234     private static native int nativeRowBytes(long nativeBitmap);
nativeConfig(long nativeBitmap)2235     private static native int nativeConfig(long nativeBitmap);
2236 
nativeGetPixel(long nativeBitmap, int x, int y)2237     private static native int nativeGetPixel(long nativeBitmap, int x, int y);
nativeGetColor(long nativeBitmap, int x, int y)2238     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)2239     private static native void nativeGetPixels(long nativeBitmap, int[] pixels,
2240                                                int offset, int stride, int x, int y,
2241                                                int width, int height);
2242 
nativeSetPixel(long nativeBitmap, int x, int y, int color)2243     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)2244     private static native void nativeSetPixels(long nativeBitmap, int[] colors,
2245                                                int offset, int stride, int x, int y,
2246                                                int width, int height);
nativeCopyPixelsToBuffer(long nativeBitmap, Buffer dst)2247     private static native void nativeCopyPixelsToBuffer(long nativeBitmap,
2248                                                         Buffer dst);
nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src)2249     private static native void nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src);
nativeGenerationId(long nativeBitmap)2250     private static native int nativeGenerationId(long nativeBitmap);
2251 
nativeCreateFromParcel(Parcel p)2252     private static native Bitmap nativeCreateFromParcel(Parcel p);
2253     // returns true on success
nativeWriteToParcel(long nativeBitmap, boolean isMutable, int density, Parcel p)2254     private static native boolean nativeWriteToParcel(long nativeBitmap,
2255                                                       boolean isMutable,
2256                                                       int density,
2257                                                       Parcel p);
2258     // returns a new bitmap built from the native bitmap's alpha, and the paint
nativeExtractAlpha(long nativeBitmap, long nativePaint, int[] offsetXY)2259     private static native Bitmap nativeExtractAlpha(long nativeBitmap,
2260                                                     long nativePaint,
2261                                                     int[] offsetXY);
2262 
nativeHasAlpha(long nativeBitmap)2263     private static native boolean nativeHasAlpha(long nativeBitmap);
nativeIsPremultiplied(long nativeBitmap)2264     private static native boolean nativeIsPremultiplied(long nativeBitmap);
nativeSetPremultiplied(long nativeBitmap, boolean isPremul)2265     private static native void nativeSetPremultiplied(long nativeBitmap,
2266                                                       boolean isPremul);
nativeSetHasAlpha(long nativeBitmap, boolean hasAlpha, boolean requestPremul)2267     private static native void nativeSetHasAlpha(long nativeBitmap,
2268                                                  boolean hasAlpha,
2269                                                  boolean requestPremul);
nativeHasMipMap(long nativeBitmap)2270     private static native boolean nativeHasMipMap(long nativeBitmap);
nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap)2271     private static native void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap);
nativeSameAs(long nativeBitmap0, long nativeBitmap1)2272     private static native boolean nativeSameAs(long nativeBitmap0, long nativeBitmap1);
nativePrepareToDraw(long nativeBitmap)2273     private static native void nativePrepareToDraw(long nativeBitmap);
nativeGetAllocationByteCount(long nativeBitmap)2274     private static native int nativeGetAllocationByteCount(long nativeBitmap);
nativeCopyPreserveInternalConfig(long nativeBitmap)2275     private static native Bitmap nativeCopyPreserveInternalConfig(long nativeBitmap);
nativeWrapHardwareBufferBitmap(HardwareBuffer buffer, long nativeColorSpace)2276     private static native Bitmap nativeWrapHardwareBufferBitmap(HardwareBuffer buffer,
2277                                                                 long nativeColorSpace);
nativeCreateGraphicBufferHandle(long nativeBitmap)2278     private static native GraphicBuffer nativeCreateGraphicBufferHandle(long nativeBitmap);
nativeComputeColorSpace(long nativePtr)2279     private static native ColorSpace nativeComputeColorSpace(long nativePtr);
nativeSetColorSpace(long nativePtr, long nativeColorSpace)2280     private static native void nativeSetColorSpace(long nativePtr, long nativeColorSpace);
nativeIsSRGB(long nativePtr)2281     private static native boolean nativeIsSRGB(long nativePtr);
nativeIsSRGBLinear(long nativePtr)2282     private static native boolean nativeIsSRGBLinear(long nativePtr);
2283 
nativeSetImmutable(long nativePtr)2284     private static native void nativeSetImmutable(long nativePtr);
2285 
2286     // ---------------- @CriticalNative -------------------
2287 
2288     @CriticalNative
nativeIsImmutable(long nativePtr)2289     private static native boolean nativeIsImmutable(long nativePtr);
2290 }
2291