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