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