Bitmap.java revision 9fbb0b5ab321d86efbc7fa8774052bfb34de9557
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 17package android.graphics; 18 19import android.annotation.CheckResult; 20import android.annotation.ColorInt; 21import android.annotation.NonNull; 22import android.os.Parcel; 23import android.os.Parcelable; 24import android.os.Trace; 25import android.util.DisplayMetrics; 26import android.util.Log; 27 28import libcore.util.NativeAllocationRegistry; 29 30import java.io.OutputStream; 31import java.nio.Buffer; 32import java.nio.ByteBuffer; 33import java.nio.IntBuffer; 34import java.nio.ShortBuffer; 35 36public final class Bitmap implements Parcelable { 37 private static final String TAG = "Bitmap"; 38 39 /** 40 * Indicates that the bitmap was created for an unknown pixel density. 41 * 42 * @see Bitmap#getDensity() 43 * @see Bitmap#setDensity(int) 44 */ 45 public static final int DENSITY_NONE = 0; 46 47 // Estimated size of the Bitmap native allocation, not including 48 // pixel data. 49 private static final long NATIVE_ALLOCATION_SIZE = 32; 50 51 // Convenience for JNI access 52 private final long mNativePtr; 53 54 private final boolean mIsMutable; 55 56 /** 57 * Represents whether the Bitmap's content is requested to be pre-multiplied. 58 * Note that isPremultiplied() does not directly return this value, because 59 * isPremultiplied() may never return true for a 565 Bitmap or a bitmap 60 * without alpha. 61 * 62 * setPremultiplied() does directly set the value so that setConfig() and 63 * setPremultiplied() aren't order dependent, despite being setters. 64 * 65 * The native bitmap's premultiplication state is kept up to date by 66 * pushing down this preference for every config change. 67 */ 68 private boolean mRequestPremultiplied; 69 70 private byte[] mNinePatchChunk; // may be null 71 private NinePatch.InsetStruct mNinePatchInsets; // may be null 72 private int mWidth; 73 private int mHeight; 74 private boolean mRecycled; 75 76 /** @hide */ 77 public int mDensity = getDefaultDensity(); 78 79 private static volatile Matrix sScaleMatrix; 80 81 private static volatile int sDefaultDensity = -1; 82 83 /** 84 * For backwards compatibility, allows the app layer to change the default 85 * density when running old apps. 86 * @hide 87 */ 88 public static void setDefaultDensity(int density) { 89 sDefaultDensity = density; 90 } 91 92 @SuppressWarnings("deprecation") 93 static int getDefaultDensity() { 94 if (sDefaultDensity >= 0) { 95 return sDefaultDensity; 96 } 97 sDefaultDensity = DisplayMetrics.DENSITY_DEVICE; 98 return sDefaultDensity; 99 } 100 101 /** 102 * Private constructor that must received an already allocated native bitmap 103 * int (pointer). 104 */ 105 // called from JNI 106 Bitmap(long nativeBitmap, int width, int height, int density, 107 boolean isMutable, boolean requestPremultiplied, 108 byte[] ninePatchChunk, NinePatch.InsetStruct ninePatchInsets) { 109 if (nativeBitmap == 0) { 110 throw new RuntimeException("internal error: native bitmap is 0"); 111 } 112 113 mWidth = width; 114 mHeight = height; 115 mIsMutable = isMutable; 116 mRequestPremultiplied = requestPremultiplied; 117 118 mNinePatchChunk = ninePatchChunk; 119 mNinePatchInsets = ninePatchInsets; 120 if (density >= 0) { 121 mDensity = density; 122 } 123 124 mNativePtr = nativeBitmap; 125 long nativeSize = NATIVE_ALLOCATION_SIZE + getAllocationByteCount(); 126 NativeAllocationRegistry registry = new NativeAllocationRegistry( 127 Bitmap.class.getClassLoader(), nativeGetNativeFinalizer(), nativeSize); 128 registry.registerNativeAllocation(this, nativeBitmap); 129 } 130 131 /** 132 * Return the pointer to the native object. 133 * @hide 134 */ 135 public long getNativeInstance() { 136 return mNativePtr; 137 } 138 139 /** 140 * Native bitmap has been reconfigured, so set premult and cached 141 * width/height values 142 */ 143 // called from JNI 144 void reinit(int width, int height, boolean requestPremultiplied) { 145 mWidth = width; 146 mHeight = height; 147 mRequestPremultiplied = requestPremultiplied; 148 } 149 150 /** 151 * <p>Returns the density for this bitmap.</p> 152 * 153 * <p>The default density is the same density as the current display, 154 * unless the current application does not support different screen 155 * densities in which case it is 156 * {@link android.util.DisplayMetrics#DENSITY_DEFAULT}. Note that 157 * compatibility mode is determined by the application that was initially 158 * loaded into a process -- applications that share the same process should 159 * all have the same compatibility, or ensure they explicitly set the 160 * density of their bitmaps appropriately.</p> 161 * 162 * @return A scaling factor of the default density or {@link #DENSITY_NONE} 163 * if the scaling factor is unknown. 164 * 165 * @see #setDensity(int) 166 * @see android.util.DisplayMetrics#DENSITY_DEFAULT 167 * @see android.util.DisplayMetrics#densityDpi 168 * @see #DENSITY_NONE 169 */ 170 public int getDensity() { 171 if (mRecycled) { 172 Log.w(TAG, "Called getDensity() on a recycle()'d bitmap! This is undefined behavior!"); 173 } 174 return mDensity; 175 } 176 177 /** 178 * <p>Specifies the density for this bitmap. When the bitmap is 179 * drawn to a Canvas that also has a density, it will be scaled 180 * appropriately.</p> 181 * 182 * @param density The density scaling factor to use with this bitmap or 183 * {@link #DENSITY_NONE} if the density is unknown. 184 * 185 * @see #getDensity() 186 * @see android.util.DisplayMetrics#DENSITY_DEFAULT 187 * @see android.util.DisplayMetrics#densityDpi 188 * @see #DENSITY_NONE 189 */ 190 public void setDensity(int density) { 191 mDensity = density; 192 } 193 194 /** 195 * <p>Modifies the bitmap to have a specified width, height, and {@link 196 * Config}, without affecting the underlying allocation backing the bitmap. 197 * Bitmap pixel data is not re-initialized for the new configuration.</p> 198 * 199 * <p>This method can be used to avoid allocating a new bitmap, instead 200 * reusing an existing bitmap's allocation for a new configuration of equal 201 * or lesser size. If the Bitmap's allocation isn't large enough to support 202 * the new configuration, an IllegalArgumentException will be thrown and the 203 * bitmap will not be modified.</p> 204 * 205 * <p>The result of {@link #getByteCount()} will reflect the new configuration, 206 * while {@link #getAllocationByteCount()} will reflect that of the initial 207 * configuration.</p> 208 * 209 * <p>Note: This may change this result of hasAlpha(). When converting to 565, 210 * the new bitmap will always be considered opaque. When converting from 565, 211 * the new bitmap will be considered non-opaque, and will respect the value 212 * set by setPremultiplied().</p> 213 * 214 * <p>WARNING: This method should NOT be called on a bitmap currently in use 215 * by the view system, Canvas, or the AndroidBitmap NDK API. It does not 216 * make guarantees about how the underlying pixel buffer is remapped to the 217 * new config, just that the allocation is reused. Additionally, the view 218 * system does not account for bitmap properties being modifying during use, 219 * e.g. while attached to drawables.</p> 220 * 221 * <p>In order to safely ensure that a Bitmap is no longer in use by the 222 * View system it is necessary to wait for a draw pass to occur after 223 * invalidate()'ing any view that had previously drawn the Bitmap in the last 224 * draw pass due to hardware acceleration's caching of draw commands. As 225 * an example, here is how this can be done for an ImageView: 226 * <pre class="prettyprint"> 227 * ImageView myImageView = ...; 228 * final Bitmap myBitmap = ...; 229 * myImageView.setImageDrawable(null); 230 * myImageView.post(new Runnable() { 231 * public void run() { 232 * // myBitmap is now no longer in use by the ImageView 233 * // and can be safely reconfigured. 234 * myBitmap.reconfigure(...); 235 * } 236 * }); 237 * </pre></p> 238 * 239 * @see #setWidth(int) 240 * @see #setHeight(int) 241 * @see #setConfig(Config) 242 */ 243 public void reconfigure(int width, int height, Config config) { 244 checkRecycled("Can't call reconfigure() on a recycled bitmap"); 245 if (width <= 0 || height <= 0) { 246 throw new IllegalArgumentException("width and height must be > 0"); 247 } 248 if (!isMutable()) { 249 throw new IllegalStateException("only mutable bitmaps may be reconfigured"); 250 } 251 252 nativeReconfigure(mNativePtr, width, height, config.nativeInt, mRequestPremultiplied); 253 mWidth = width; 254 mHeight = height; 255 } 256 257 /** 258 * <p>Convenience method for calling {@link #reconfigure(int, int, Config)} 259 * with the current height and config.</p> 260 * 261 * <p>WARNING: this method should not be used on bitmaps currently used by 262 * the view system, see {@link #reconfigure(int, int, Config)} for more 263 * details.</p> 264 * 265 * @see #reconfigure(int, int, Config) 266 * @see #setHeight(int) 267 * @see #setConfig(Config) 268 */ 269 public void setWidth(int width) { 270 reconfigure(width, getHeight(), getConfig()); 271 } 272 273 /** 274 * <p>Convenience method for calling {@link #reconfigure(int, int, Config)} 275 * with the current width and config.</p> 276 * 277 * <p>WARNING: this method should not be used on bitmaps currently used by 278 * the view system, see {@link #reconfigure(int, int, Config)} for more 279 * details.</p> 280 * 281 * @see #reconfigure(int, int, Config) 282 * @see #setWidth(int) 283 * @see #setConfig(Config) 284 */ 285 public void setHeight(int height) { 286 reconfigure(getWidth(), height, getConfig()); 287 } 288 289 /** 290 * <p>Convenience method for calling {@link #reconfigure(int, int, Config)} 291 * with the current height and width.</p> 292 * 293 * <p>WARNING: this method should not be used on bitmaps currently used by 294 * the view system, see {@link #reconfigure(int, int, Config)} for more 295 * details.</p> 296 * 297 * @see #reconfigure(int, int, Config) 298 * @see #setWidth(int) 299 * @see #setHeight(int) 300 */ 301 public void setConfig(Config config) { 302 reconfigure(getWidth(), getHeight(), config); 303 } 304 305 /** 306 * Sets the nine patch chunk. 307 * 308 * @param chunk The definition of the nine patch 309 * 310 * @hide 311 */ 312 public void setNinePatchChunk(byte[] chunk) { 313 mNinePatchChunk = chunk; 314 } 315 316 /** 317 * Free the native object associated with this bitmap, and clear the 318 * reference to the pixel data. This will not free the pixel data synchronously; 319 * it simply allows it to be garbage collected if there are no other references. 320 * The bitmap is marked as "dead", meaning it will throw an exception if 321 * getPixels() or setPixels() is called, and will draw nothing. This operation 322 * cannot be reversed, so it should only be called if you are sure there are no 323 * further uses for the bitmap. This is an advanced call, and normally need 324 * not be called, since the normal GC process will free up this memory when 325 * there are no more references to this bitmap. 326 */ 327 public void recycle() { 328 if (!mRecycled && mNativePtr != 0) { 329 if (nativeRecycle(mNativePtr)) { 330 // return value indicates whether native pixel object was actually recycled. 331 // false indicates that it is still in use at the native level and these 332 // objects should not be collected now. They will be collected later when the 333 // Bitmap itself is collected. 334 mNinePatchChunk = null; 335 } 336 mRecycled = true; 337 } 338 } 339 340 /** 341 * Returns true if this bitmap has been recycled. If so, then it is an error 342 * to try to access its pixels, and the bitmap will not draw. 343 * 344 * @return true if the bitmap has been recycled 345 */ 346 public final boolean isRecycled() { 347 return mRecycled; 348 } 349 350 /** 351 * Returns the generation ID of this bitmap. The generation ID changes 352 * whenever the bitmap is modified. This can be used as an efficient way to 353 * check if a bitmap has changed. 354 * 355 * @return The current generation ID for this bitmap. 356 */ 357 public int getGenerationId() { 358 if (mRecycled) { 359 Log.w(TAG, "Called getGenerationId() on a recycle()'d bitmap! This is undefined behavior!"); 360 } 361 return nativeGenerationId(mNativePtr); 362 } 363 364 /** 365 * This is called by methods that want to throw an exception if the bitmap 366 * has already been recycled. 367 */ 368 private void checkRecycled(String errorMessage) { 369 if (mRecycled) { 370 throw new IllegalStateException(errorMessage); 371 } 372 } 373 374 /** 375 * Common code for checking that x and y are >= 0 376 * 377 * @param x x coordinate to ensure is >= 0 378 * @param y y coordinate to ensure is >= 0 379 */ 380 private static void checkXYSign(int x, int y) { 381 if (x < 0) { 382 throw new IllegalArgumentException("x must be >= 0"); 383 } 384 if (y < 0) { 385 throw new IllegalArgumentException("y must be >= 0"); 386 } 387 } 388 389 /** 390 * Common code for checking that width and height are > 0 391 * 392 * @param width width to ensure is > 0 393 * @param height height to ensure is > 0 394 */ 395 private static void checkWidthHeight(int width, int height) { 396 if (width <= 0) { 397 throw new IllegalArgumentException("width must be > 0"); 398 } 399 if (height <= 0) { 400 throw new IllegalArgumentException("height must be > 0"); 401 } 402 } 403 404 /** 405 * Possible bitmap configurations. A bitmap configuration describes 406 * how pixels are stored. This affects the quality (color depth) as 407 * well as the ability to display transparent/translucent colors. 408 */ 409 public enum Config { 410 // these native values must match up with the enum in SkBitmap.h 411 412 /** 413 * Each pixel is stored as a single translucency (alpha) channel. 414 * This is very useful to efficiently store masks for instance. 415 * No color information is stored. 416 * With this configuration, each pixel requires 1 byte of memory. 417 */ 418 ALPHA_8 (1), 419 420 /** 421 * Each pixel is stored on 2 bytes and only the RGB channels are 422 * encoded: red is stored with 5 bits of precision (32 possible 423 * values), green is stored with 6 bits of precision (64 possible 424 * values) and blue is stored with 5 bits of precision. 425 * 426 * This configuration can produce slight visual artifacts depending 427 * on the configuration of the source. For instance, without 428 * dithering, the result might show a greenish tint. To get better 429 * results dithering should be applied. 430 * 431 * This configuration may be useful when using opaque bitmaps 432 * that do not require high color fidelity. 433 */ 434 RGB_565 (3), 435 436 /** 437 * Each pixel is stored on 2 bytes. The three RGB color channels 438 * and the alpha channel (translucency) are stored with a 4 bits 439 * precision (16 possible values.) 440 * 441 * This configuration is mostly useful if the application needs 442 * to store translucency information but also needs to save 443 * memory. 444 * 445 * It is recommended to use {@link #ARGB_8888} instead of this 446 * configuration. 447 * 448 * Note: as of {@link android.os.Build.VERSION_CODES#KITKAT}, 449 * any bitmap created with this configuration will be created 450 * using {@link #ARGB_8888} instead. 451 * 452 * @deprecated Because of the poor quality of this configuration, 453 * it is advised to use {@link #ARGB_8888} instead. 454 */ 455 @Deprecated 456 ARGB_4444 (4), 457 458 /** 459 * Each pixel is stored on 4 bytes. Each channel (RGB and alpha 460 * for translucency) is stored with 8 bits of precision (256 461 * possible values.) 462 * 463 * This configuration is very flexible and offers the best 464 * quality. It should be used whenever possible. 465 */ 466 ARGB_8888 (5), 467 468 469 /** 470 * Special configuration, when bitmap is stored only in graphic memory. 471 * Bitmaps in this configuration are always immutable. 472 * 473 * It is optimal for cases, when the only operation with the bitmap is to draw it on a 474 * screen. 475 */ 476 HARDWARE (6); 477 478 final int nativeInt; 479 480 private static Config sConfigs[] = { 481 null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888, HARDWARE 482 }; 483 484 Config(int ni) { 485 this.nativeInt = ni; 486 } 487 488 static Config nativeToConfig(int ni) { 489 return sConfigs[ni]; 490 } 491 } 492 493 /** 494 * <p>Copy the bitmap's pixels into the specified buffer (allocated by the 495 * caller). An exception is thrown if the buffer is not large enough to 496 * hold all of the pixels (taking into account the number of bytes per 497 * pixel) or if the Buffer subclass is not one of the support types 498 * (ByteBuffer, ShortBuffer, IntBuffer).</p> 499 * <p>The content of the bitmap is copied into the buffer as-is. This means 500 * that if this bitmap stores its pixels pre-multiplied 501 * (see {@link #isPremultiplied()}, the values in the buffer will also be 502 * pre-multiplied.</p> 503 * <p>After this method returns, the current position of the buffer is 504 * updated: the position is incremented by the number of elements written 505 * in the buffer.</p> 506 */ 507 public void copyPixelsToBuffer(Buffer dst) { 508 int elements = dst.remaining(); 509 int shift; 510 if (dst instanceof ByteBuffer) { 511 shift = 0; 512 } else if (dst instanceof ShortBuffer) { 513 shift = 1; 514 } else if (dst instanceof IntBuffer) { 515 shift = 2; 516 } else { 517 throw new RuntimeException("unsupported Buffer subclass"); 518 } 519 520 long bufferSize = (long)elements << shift; 521 long pixelSize = getByteCount(); 522 523 if (bufferSize < pixelSize) { 524 throw new RuntimeException("Buffer not large enough for pixels"); 525 } 526 527 nativeCopyPixelsToBuffer(mNativePtr, dst); 528 529 // now update the buffer's position 530 int position = dst.position(); 531 position += pixelSize >> shift; 532 dst.position(position); 533 } 534 535 /** 536 * <p>Copy the pixels from the buffer, beginning at the current position, 537 * overwriting the bitmap's pixels. The data in the buffer is not changed 538 * in any way (unlike setPixels(), which converts from unpremultipled 32bit 539 * to whatever the bitmap's native format is.</p> 540 * <p>After this method returns, the current position of the buffer is 541 * updated: the position is incremented by the number of elements read from 542 * the buffer. If you need to read the bitmap from the buffer again you must 543 * first rewind the buffer.</p> 544 */ 545 public void copyPixelsFromBuffer(Buffer src) { 546 checkRecycled("copyPixelsFromBuffer called on recycled bitmap"); 547 548 int elements = src.remaining(); 549 int shift; 550 if (src instanceof ByteBuffer) { 551 shift = 0; 552 } else if (src instanceof ShortBuffer) { 553 shift = 1; 554 } else if (src instanceof IntBuffer) { 555 shift = 2; 556 } else { 557 throw new RuntimeException("unsupported Buffer subclass"); 558 } 559 560 long bufferBytes = (long) elements << shift; 561 long bitmapBytes = getByteCount(); 562 563 if (bufferBytes < bitmapBytes) { 564 throw new RuntimeException("Buffer not large enough for pixels"); 565 } 566 567 nativeCopyPixelsFromBuffer(mNativePtr, src); 568 569 // now update the buffer's position 570 int position = src.position(); 571 position += bitmapBytes >> shift; 572 src.position(position); 573 } 574 575 /** 576 * Tries to make a new bitmap based on the dimensions of this bitmap, 577 * setting the new bitmap's config to the one specified, and then copying 578 * this bitmap's pixels into the new bitmap. If the conversion is not 579 * supported, or the allocator fails, then this returns NULL. The returned 580 * bitmap initially has the same density as the original. 581 * 582 * @param config The desired config for the resulting bitmap 583 * @param isMutable True if the resulting bitmap should be mutable (i.e. 584 * its pixels can be modified) 585 * @return the new bitmap, or null if the copy could not be made. 586 */ 587 public Bitmap copy(Config config, boolean isMutable) { 588 checkRecycled("Can't copy a recycled bitmap"); 589 Bitmap b = nativeCopy(mNativePtr, config.nativeInt, isMutable); 590 if (b != null) { 591 b.setPremultiplied(mRequestPremultiplied); 592 b.mDensity = mDensity; 593 } 594 return b; 595 } 596 597 /** 598 * Creates a new immutable bitmap backed by ashmem which can efficiently 599 * be passed between processes. 600 * 601 * @hide 602 */ 603 public Bitmap createAshmemBitmap() { 604 checkRecycled("Can't copy a recycled bitmap"); 605 Bitmap b = nativeCopyAshmem(mNativePtr); 606 if (b != null) { 607 b.setPremultiplied(mRequestPremultiplied); 608 b.mDensity = mDensity; 609 } 610 return b; 611 } 612 613 /** 614 * Creates a new immutable bitmap backed by ashmem which can efficiently 615 * be passed between processes. 616 * 617 * @hide 618 */ 619 public Bitmap createAshmemBitmap(Config config) { 620 checkRecycled("Can't copy a recycled bitmap"); 621 Bitmap b = nativeCopyAshmemConfig(mNativePtr, config.nativeInt); 622 if (b != null) { 623 b.setPremultiplied(mRequestPremultiplied); 624 b.mDensity = mDensity; 625 } 626 return b; 627 } 628 629 /** 630 * Creates a new bitmap, scaled from an existing bitmap, when possible. If the 631 * specified width and height are the same as the current width and height of 632 * the source bitmap, the source bitmap is returned and no new bitmap is 633 * created. 634 * 635 * @param src The source bitmap. 636 * @param dstWidth The new bitmap's desired width. 637 * @param dstHeight The new bitmap's desired height. 638 * @param filter true if the source should be filtered. 639 * @return The new scaled bitmap or the source bitmap if no scaling is required. 640 * @throws IllegalArgumentException if width is <= 0, or height is <= 0 641 */ 642 public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, 643 boolean filter) { 644 Matrix m; 645 synchronized (Bitmap.class) { 646 // small pool of just 1 matrix 647 m = sScaleMatrix; 648 sScaleMatrix = null; 649 } 650 651 if (m == null) { 652 m = new Matrix(); 653 } 654 655 final int width = src.getWidth(); 656 final int height = src.getHeight(); 657 final float sx = dstWidth / (float)width; 658 final float sy = dstHeight / (float)height; 659 m.setScale(sx, sy); 660 Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter); 661 662 synchronized (Bitmap.class) { 663 // do we need to check for null? why not just assign everytime? 664 if (sScaleMatrix == null) { 665 sScaleMatrix = m; 666 } 667 } 668 669 return b; 670 } 671 672 /** 673 * Returns an immutable bitmap from the source bitmap. The new bitmap may 674 * be the same object as source, or a copy may have been made. It is 675 * initialized with the same density as the original bitmap. 676 */ 677 public static Bitmap createBitmap(Bitmap src) { 678 return createBitmap(src, 0, 0, src.getWidth(), src.getHeight()); 679 } 680 681 /** 682 * Returns an immutable bitmap from the specified subset of the source 683 * bitmap. The new bitmap may be the same object as source, or a copy may 684 * have been made. It is initialized with the same density as the original 685 * bitmap. 686 * 687 * @param source The bitmap we are subsetting 688 * @param x The x coordinate of the first pixel in source 689 * @param y The y coordinate of the first pixel in source 690 * @param width The number of pixels in each row 691 * @param height The number of rows 692 * @return A copy of a subset of the source bitmap or the source bitmap itself. 693 * @throws IllegalArgumentException if the x, y, width, height values are 694 * outside of the dimensions of the source bitmap, or width is <= 0, 695 * or height is <= 0 696 */ 697 public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) { 698 return createBitmap(source, x, y, width, height, null, false); 699 } 700 701 /** 702 * Returns an immutable bitmap from subset of the source bitmap, 703 * transformed by the optional matrix. The new bitmap may be the 704 * same object as source, or a copy may have been made. It is 705 * initialized with the same density as the original bitmap. 706 * 707 * If the source bitmap is immutable and the requested subset is the 708 * same as the source bitmap itself, then the source bitmap is 709 * returned and no new bitmap is created. 710 * 711 * @param source The bitmap we are subsetting 712 * @param x The x coordinate of the first pixel in source 713 * @param y The y coordinate of the first pixel in source 714 * @param width The number of pixels in each row 715 * @param height The number of rows 716 * @param m Optional matrix to be applied to the pixels 717 * @param filter true if the source should be filtered. 718 * Only applies if the matrix contains more than just 719 * translation. 720 * @return A bitmap that represents the specified subset of source 721 * @throws IllegalArgumentException if the x, y, width, height values are 722 * outside of the dimensions of the source bitmap, or width is <= 0, 723 * or height is <= 0 724 */ 725 public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, 726 Matrix m, boolean filter) { 727 728 checkXYSign(x, y); 729 checkWidthHeight(width, height); 730 if (x + width > source.getWidth()) { 731 throw new IllegalArgumentException("x + width must be <= bitmap.width()"); 732 } 733 if (y + height > source.getHeight()) { 734 throw new IllegalArgumentException("y + height must be <= bitmap.height()"); 735 } 736 737 // check if we can just return our argument unchanged 738 if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() && 739 height == source.getHeight() && (m == null || m.isIdentity())) { 740 return source; 741 } 742 743 int neww = width; 744 int newh = height; 745 Canvas canvas = new Canvas(); 746 Bitmap bitmap; 747 Paint paint; 748 749 Rect srcR = new Rect(x, y, x + width, y + height); 750 RectF dstR = new RectF(0, 0, width, height); 751 752 Config newConfig = Config.ARGB_8888; 753 final Config config = source.getConfig(); 754 // GIF files generate null configs, assume ARGB_8888 755 if (config != null) { 756 switch (config) { 757 case RGB_565: 758 newConfig = Config.RGB_565; 759 break; 760 case ALPHA_8: 761 newConfig = Config.ALPHA_8; 762 break; 763 //noinspection deprecation 764 case ARGB_4444: 765 case ARGB_8888: 766 default: 767 newConfig = Config.ARGB_8888; 768 break; 769 } 770 } 771 772 if (m == null || m.isIdentity()) { 773 bitmap = createBitmap(neww, newh, newConfig, source.hasAlpha()); 774 paint = null; // not needed 775 } else { 776 final boolean transformed = !m.rectStaysRect(); 777 778 RectF deviceR = new RectF(); 779 m.mapRect(deviceR, dstR); 780 781 neww = Math.round(deviceR.width()); 782 newh = Math.round(deviceR.height()); 783 784 bitmap = createBitmap(neww, newh, transformed ? Config.ARGB_8888 : newConfig, 785 transformed || source.hasAlpha()); 786 787 canvas.translate(-deviceR.left, -deviceR.top); 788 canvas.concat(m); 789 790 paint = new Paint(); 791 paint.setFilterBitmap(filter); 792 if (transformed) { 793 paint.setAntiAlias(true); 794 } 795 } 796 797 // The new bitmap was created from a known bitmap source so assume that 798 // they use the same density 799 bitmap.mDensity = source.mDensity; 800 bitmap.setHasAlpha(source.hasAlpha()); 801 bitmap.setPremultiplied(source.mRequestPremultiplied); 802 803 canvas.setBitmap(bitmap); 804 canvas.drawBitmap(source, srcR, dstR, paint); 805 canvas.setBitmap(null); 806 807 return bitmap; 808 } 809 810 /** 811 * Returns a mutable bitmap with the specified width and height. Its 812 * initial density is as per {@link #getDensity}. 813 * 814 * @param width The width of the bitmap 815 * @param height The height of the bitmap 816 * @param config The bitmap config to create. 817 * @throws IllegalArgumentException if the width or height are <= 0, or if 818 * Config is Config.HARDWARE, because hardware bitmaps are always immutable 819 */ 820 public static Bitmap createBitmap(int width, int height, Config config) { 821 return createBitmap(width, height, config, true); 822 } 823 824 /** 825 * Returns a mutable bitmap with the specified width and height. Its 826 * initial density is determined from the given {@link DisplayMetrics}. 827 * 828 * @param display Display metrics for the display this bitmap will be 829 * drawn on. 830 * @param width The width of the bitmap 831 * @param height The height of the bitmap 832 * @param config The bitmap config to create. 833 * @throws IllegalArgumentException if the width or height are <= 0, or if 834 * Config is Config.HARDWARE, because hardware bitmaps are always immutable 835 */ 836 public static Bitmap createBitmap(DisplayMetrics display, int width, 837 int height, Config config) { 838 return createBitmap(display, width, height, config, true); 839 } 840 841 /** 842 * Returns a mutable bitmap with the specified width and height. Its 843 * initial density is as per {@link #getDensity}. 844 * 845 * @param width The width of the bitmap 846 * @param height The height of the bitmap 847 * @param config The bitmap config to create. 848 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the 849 * bitmap as opaque. Doing so will clear the bitmap in black 850 * instead of transparent. 851 * 852 * @throws IllegalArgumentException if the width or height are <= 0, or if 853 * Config is Config.HARDWARE, because hardware bitmaps are always immutable 854 */ 855 private static Bitmap createBitmap(int width, int height, Config config, boolean hasAlpha) { 856 return createBitmap(null, width, height, config, hasAlpha); 857 } 858 859 /** 860 * Returns a mutable bitmap with the specified width and height. Its 861 * initial density is determined from the given {@link DisplayMetrics}. 862 * 863 * @param display Display metrics for the display this bitmap will be 864 * drawn on. 865 * @param width The width of the bitmap 866 * @param height The height of the bitmap 867 * @param config The bitmap config to create. 868 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the 869 * bitmap as opaque. Doing so will clear the bitmap in black 870 * instead of transparent. 871 * 872 * @throws IllegalArgumentException if the width or height are <= 0, or if 873 * Config is Config.HARDWARE, because hardware bitmaps are always immutable 874 */ 875 private static Bitmap createBitmap(DisplayMetrics display, int width, int height, 876 Config config, boolean hasAlpha) { 877 if (width <= 0 || height <= 0) { 878 throw new IllegalArgumentException("width and height must be > 0"); 879 } 880 if (config == Config.HARDWARE) { 881 throw new IllegalArgumentException("can't create mutable bitmap with Config.HARDWARE"); 882 } 883 Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true); 884 if (display != null) { 885 bm.mDensity = display.densityDpi; 886 } 887 bm.setHasAlpha(hasAlpha); 888 if (config == Config.ARGB_8888 && !hasAlpha) { 889 nativeErase(bm.mNativePtr, 0xff000000); 890 } 891 // No need to initialize the bitmap to zeroes with other configs; 892 // it is backed by a VM byte array which is by definition preinitialized 893 // to all zeroes. 894 return bm; 895 } 896 897 /** 898 * Returns a immutable bitmap with the specified width and height, with each 899 * pixel value set to the corresponding value in the colors array. Its 900 * initial density is as per {@link #getDensity}. 901 * 902 * @param colors Array of {@link Color} used to initialize the pixels. 903 * @param offset Number of values to skip before the first color in the 904 * array of colors. 905 * @param stride Number of colors in the array between rows (must be >= 906 * width or <= -width). 907 * @param width The width of the bitmap 908 * @param height The height of the bitmap 909 * @param config The bitmap config to create. If the config does not 910 * support per-pixel alpha (e.g. RGB_565), then the alpha 911 * bytes in the colors[] will be ignored (assumed to be FF) 912 * @throws IllegalArgumentException if the width or height are <= 0, or if 913 * the color array's length is less than the number of pixels. 914 */ 915 public static Bitmap createBitmap(int colors[], int offset, int stride, 916 int width, int height, Config config) { 917 return createBitmap(null, colors, offset, stride, width, height, config); 918 } 919 920 /** 921 * Returns a immutable bitmap with the specified width and height, with each 922 * pixel value set to the corresponding value in the colors array. Its 923 * initial density is determined from the given {@link DisplayMetrics}. 924 * 925 * @param display Display metrics for the display this bitmap will be 926 * drawn on. 927 * @param colors Array of {@link Color} used to initialize the pixels. 928 * @param offset Number of values to skip before the first color in the 929 * array of colors. 930 * @param stride Number of colors in the array between rows (must be >= 931 * width or <= -width). 932 * @param width The width of the bitmap 933 * @param height The height of the bitmap 934 * @param config The bitmap config to create. If the config does not 935 * support per-pixel alpha (e.g. RGB_565), then the alpha 936 * bytes in the colors[] will be ignored (assumed to be FF) 937 * @throws IllegalArgumentException if the width or height are <= 0, or if 938 * the color array's length is less than the number of pixels. 939 */ 940 public static Bitmap createBitmap(DisplayMetrics display, int colors[], 941 int offset, int stride, int width, int height, Config config) { 942 943 checkWidthHeight(width, height); 944 if (Math.abs(stride) < width) { 945 throw new IllegalArgumentException("abs(stride) must be >= width"); 946 } 947 int lastScanline = offset + (height - 1) * stride; 948 int length = colors.length; 949 if (offset < 0 || (offset + width > length) || lastScanline < 0 || 950 (lastScanline + width > length)) { 951 throw new ArrayIndexOutOfBoundsException(); 952 } 953 if (width <= 0 || height <= 0) { 954 throw new IllegalArgumentException("width and height must be > 0"); 955 } 956 Bitmap bm = nativeCreate(colors, offset, stride, width, height, 957 config.nativeInt, false); 958 if (display != null) { 959 bm.mDensity = display.densityDpi; 960 } 961 return bm; 962 } 963 964 /** 965 * Returns a immutable bitmap with the specified width and height, with each 966 * pixel value set to the corresponding value in the colors array. Its 967 * initial density is as per {@link #getDensity}. 968 * 969 * @param colors Array of {@link Color} used to initialize the pixels. 970 * This array must be at least as large as width * height. 971 * @param width The width of the bitmap 972 * @param height The height of the bitmap 973 * @param config The bitmap config to create. If the config does not 974 * support per-pixel alpha (e.g. RGB_565), then the alpha 975 * bytes in the colors[] will be ignored (assumed to be FF) 976 * @throws IllegalArgumentException if the width or height are <= 0, or if 977 * the color array's length is less than the number of pixels. 978 */ 979 public static Bitmap createBitmap(int colors[], int width, int height, Config config) { 980 return createBitmap(null, colors, 0, width, width, height, config); 981 } 982 983 /** 984 * Returns a immutable bitmap with the specified width and height, with each 985 * pixel value set to the corresponding value in the colors array. Its 986 * initial density is determined from the given {@link DisplayMetrics}. 987 * 988 * @param display Display metrics for the display this bitmap will be 989 * drawn on. 990 * @param colors Array of {@link Color} used to initialize the pixels. 991 * This array must be at least as large as width * height. 992 * @param width The width of the bitmap 993 * @param height The height of the bitmap 994 * @param config The bitmap config to create. If the config does not 995 * support per-pixel alpha (e.g. RGB_565), then the alpha 996 * bytes in the colors[] will be ignored (assumed to be FF) 997 * @throws IllegalArgumentException if the width or height are <= 0, or if 998 * the color array's length is less than the number of pixels. 999 */ 1000 public static Bitmap createBitmap(DisplayMetrics display, int colors[], 1001 int width, int height, Config config) { 1002 return createBitmap(display, colors, 0, width, width, height, config); 1003 } 1004 1005 /** 1006 * Returns an optional array of private data, used by the UI system for 1007 * some bitmaps. Not intended to be called by applications. 1008 */ 1009 public byte[] getNinePatchChunk() { 1010 return mNinePatchChunk; 1011 } 1012 1013 /** 1014 * Populates a rectangle with the bitmap's optical insets. 1015 * 1016 * @param outInsets Rect to populate with optical insets 1017 * @hide 1018 */ 1019 public void getOpticalInsets(@NonNull Rect outInsets) { 1020 if (mNinePatchInsets == null) { 1021 outInsets.setEmpty(); 1022 } else { 1023 outInsets.set(mNinePatchInsets.opticalRect); 1024 } 1025 } 1026 1027 /** @hide */ 1028 public NinePatch.InsetStruct getNinePatchInsets() { 1029 return mNinePatchInsets; 1030 } 1031 1032 /** 1033 * Specifies the known formats a bitmap can be compressed into 1034 */ 1035 public enum CompressFormat { 1036 JPEG (0), 1037 PNG (1), 1038 WEBP (2); 1039 1040 CompressFormat(int nativeInt) { 1041 this.nativeInt = nativeInt; 1042 } 1043 final int nativeInt; 1044 } 1045 1046 /** 1047 * Number of bytes of temp storage we use for communicating between the 1048 * native compressor and the java OutputStream. 1049 */ 1050 private final static int WORKING_COMPRESS_STORAGE = 4096; 1051 1052 /** 1053 * Write a compressed version of the bitmap to the specified outputstream. 1054 * If this returns true, the bitmap can be reconstructed by passing a 1055 * corresponding inputstream to BitmapFactory.decodeStream(). Note: not 1056 * all Formats support all bitmap configs directly, so it is possible that 1057 * the returned bitmap from BitmapFactory could be in a different bitdepth, 1058 * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque 1059 * pixels). 1060 * 1061 * @param format The format of the compressed image 1062 * @param quality Hint to the compressor, 0-100. 0 meaning compress for 1063 * small size, 100 meaning compress for max quality. Some 1064 * formats, like PNG which is lossless, will ignore the 1065 * quality setting 1066 * @param stream The outputstream to write the compressed data. 1067 * @return true if successfully compressed to the specified stream. 1068 */ 1069 public boolean compress(CompressFormat format, int quality, OutputStream stream) { 1070 checkRecycled("Can't compress a recycled bitmap"); 1071 // do explicit check before calling the native method 1072 if (stream == null) { 1073 throw new NullPointerException(); 1074 } 1075 if (quality < 0 || quality > 100) { 1076 throw new IllegalArgumentException("quality must be 0..100"); 1077 } 1078 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress"); 1079 boolean result = nativeCompress(mNativePtr, format.nativeInt, 1080 quality, stream, new byte[WORKING_COMPRESS_STORAGE]); 1081 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 1082 return result; 1083 } 1084 1085 /** 1086 * Returns true if the bitmap is marked as mutable (i.e. can be drawn into) 1087 */ 1088 public final boolean isMutable() { 1089 return mIsMutable; 1090 } 1091 1092 /** 1093 * <p>Indicates whether pixels stored in this bitmaps are stored pre-multiplied. 1094 * When a pixel is pre-multiplied, the RGB components have been multiplied by 1095 * the alpha component. For instance, if the original color is a 50% 1096 * translucent red <code>(128, 255, 0, 0)</code>, the pre-multiplied form is 1097 * <code>(128, 128, 0, 0)</code>.</p> 1098 * 1099 * <p>This method always returns false if {@link #getConfig()} is 1100 * {@link Bitmap.Config#RGB_565}.</p> 1101 * 1102 * <p>The return value is undefined if {@link #getConfig()} is 1103 * {@link Bitmap.Config#ALPHA_8}.</p> 1104 * 1105 * <p>This method only returns true if {@link #hasAlpha()} returns true. 1106 * A bitmap with no alpha channel can be used both as a pre-multiplied and 1107 * as a non pre-multiplied bitmap.</p> 1108 * 1109 * <p>Only pre-multiplied bitmaps may be drawn by the view system or 1110 * {@link Canvas}. If a non-pre-multiplied bitmap with an alpha channel is 1111 * drawn to a Canvas, a RuntimeException will be thrown.</p> 1112 * 1113 * @return true if the underlying pixels have been pre-multiplied, false 1114 * otherwise 1115 * 1116 * @see Bitmap#setPremultiplied(boolean) 1117 * @see BitmapFactory.Options#inPremultiplied 1118 */ 1119 public final boolean isPremultiplied() { 1120 if (mRecycled) { 1121 Log.w(TAG, "Called isPremultiplied() on a recycle()'d bitmap! This is undefined behavior!"); 1122 } 1123 return nativeIsPremultiplied(mNativePtr); 1124 } 1125 1126 /** 1127 * Sets whether the bitmap should treat its data as pre-multiplied. 1128 * 1129 * <p>Bitmaps are always treated as pre-multiplied by the view system and 1130 * {@link Canvas} for performance reasons. Storing un-pre-multiplied data in 1131 * a Bitmap (through {@link #setPixel}, {@link #setPixels}, or {@link 1132 * BitmapFactory.Options#inPremultiplied BitmapFactory.Options.inPremultiplied}) 1133 * can lead to incorrect blending if drawn by the framework.</p> 1134 * 1135 * <p>This method will not affect the behavior of a bitmap without an alpha 1136 * channel, or if {@link #hasAlpha()} returns false.</p> 1137 * 1138 * <p>Calling {@link #createBitmap} or {@link #createScaledBitmap} with a source 1139 * Bitmap whose colors are not pre-multiplied may result in a RuntimeException, 1140 * since those functions require drawing the source, which is not supported for 1141 * un-pre-multiplied Bitmaps.</p> 1142 * 1143 * @see Bitmap#isPremultiplied() 1144 * @see BitmapFactory.Options#inPremultiplied 1145 */ 1146 public final void setPremultiplied(boolean premultiplied) { 1147 checkRecycled("setPremultiplied called on a recycled bitmap"); 1148 mRequestPremultiplied = premultiplied; 1149 nativeSetPremultiplied(mNativePtr, premultiplied); 1150 } 1151 1152 /** Returns the bitmap's width */ 1153 public final int getWidth() { 1154 if (mRecycled) { 1155 Log.w(TAG, "Called getWidth() on a recycle()'d bitmap! This is undefined behavior!"); 1156 } 1157 return mWidth; 1158 } 1159 1160 /** Returns the bitmap's height */ 1161 public final int getHeight() { 1162 if (mRecycled) { 1163 Log.w(TAG, "Called getHeight() on a recycle()'d bitmap! This is undefined behavior!"); 1164 } 1165 return mHeight; 1166 } 1167 1168 /** 1169 * Convenience for calling {@link #getScaledWidth(int)} with the target 1170 * density of the given {@link Canvas}. 1171 */ 1172 public int getScaledWidth(Canvas canvas) { 1173 return scaleFromDensity(getWidth(), mDensity, canvas.mDensity); 1174 } 1175 1176 /** 1177 * Convenience for calling {@link #getScaledHeight(int)} with the target 1178 * density of the given {@link Canvas}. 1179 */ 1180 public int getScaledHeight(Canvas canvas) { 1181 return scaleFromDensity(getHeight(), mDensity, canvas.mDensity); 1182 } 1183 1184 /** 1185 * Convenience for calling {@link #getScaledWidth(int)} with the target 1186 * density of the given {@link DisplayMetrics}. 1187 */ 1188 public int getScaledWidth(DisplayMetrics metrics) { 1189 return scaleFromDensity(getWidth(), mDensity, metrics.densityDpi); 1190 } 1191 1192 /** 1193 * Convenience for calling {@link #getScaledHeight(int)} with the target 1194 * density of the given {@link DisplayMetrics}. 1195 */ 1196 public int getScaledHeight(DisplayMetrics metrics) { 1197 return scaleFromDensity(getHeight(), mDensity, metrics.densityDpi); 1198 } 1199 1200 /** 1201 * Convenience method that returns the width of this bitmap divided 1202 * by the density scale factor. 1203 * 1204 * @param targetDensity The density of the target canvas of the bitmap. 1205 * @return The scaled width of this bitmap, according to the density scale factor. 1206 */ 1207 public int getScaledWidth(int targetDensity) { 1208 return scaleFromDensity(getWidth(), mDensity, targetDensity); 1209 } 1210 1211 /** 1212 * Convenience method that returns the height of this bitmap divided 1213 * by the density scale factor. 1214 * 1215 * @param targetDensity The density of the target canvas of the bitmap. 1216 * @return The scaled height of this bitmap, according to the density scale factor. 1217 */ 1218 public int getScaledHeight(int targetDensity) { 1219 return scaleFromDensity(getHeight(), mDensity, targetDensity); 1220 } 1221 1222 /** 1223 * @hide 1224 */ 1225 static public int scaleFromDensity(int size, int sdensity, int tdensity) { 1226 if (sdensity == DENSITY_NONE || tdensity == DENSITY_NONE || sdensity == tdensity) { 1227 return size; 1228 } 1229 1230 // Scale by tdensity / sdensity, rounding up. 1231 return ((size * tdensity) + (sdensity >> 1)) / sdensity; 1232 } 1233 1234 /** 1235 * Return the number of bytes between rows in the bitmap's pixels. Note that 1236 * this refers to the pixels as stored natively by the bitmap. If you call 1237 * getPixels() or setPixels(), then the pixels are uniformly treated as 1238 * 32bit values, packed according to the Color class. 1239 * 1240 * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, this method 1241 * should not be used to calculate the memory usage of the bitmap. Instead, 1242 * see {@link #getAllocationByteCount()}. 1243 * 1244 * @return number of bytes between rows of the native bitmap pixels. 1245 */ 1246 public final int getRowBytes() { 1247 if (mRecycled) { 1248 Log.w(TAG, "Called getRowBytes() on a recycle()'d bitmap! This is undefined behavior!"); 1249 } 1250 return nativeRowBytes(mNativePtr); 1251 } 1252 1253 /** 1254 * Returns the minimum number of bytes that can be used to store this bitmap's pixels. 1255 * 1256 * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can 1257 * no longer be used to determine memory usage of a bitmap. See {@link 1258 * #getAllocationByteCount()}.</p> 1259 */ 1260 public final int getByteCount() { 1261 if (mRecycled) { 1262 Log.w(TAG, "Called getByteCount() on a recycle()'d bitmap! " 1263 + "This is undefined behavior!"); 1264 return 0; 1265 } 1266 // int result permits bitmaps up to 46,340 x 46,340 1267 return getRowBytes() * getHeight(); 1268 } 1269 1270 /** 1271 * Returns the size of the allocated memory used to store this bitmap's pixels. 1272 * 1273 * <p>This can be larger than the result of {@link #getByteCount()} if a bitmap is reused to 1274 * decode other bitmaps of smaller size, or by manual reconfiguration. See {@link 1275 * #reconfigure(int, int, Config)}, {@link #setWidth(int)}, {@link #setHeight(int)}, {@link 1276 * #setConfig(Bitmap.Config)}, and {@link BitmapFactory.Options#inBitmap 1277 * BitmapFactory.Options.inBitmap}. If a bitmap is not modified in this way, this value will be 1278 * the same as that returned by {@link #getByteCount()}.</p> 1279 * 1280 * <p>This value will not change over the lifetime of a Bitmap.</p> 1281 * 1282 * @see #reconfigure(int, int, Config) 1283 */ 1284 public final int getAllocationByteCount() { 1285 if (mRecycled) { 1286 Log.w(TAG, "Called getAllocationByteCount() on a recycle()'d bitmap! " 1287 + "This is undefined behavior!"); 1288 return 0; 1289 } 1290 return nativeGetAllocationByteCount(mNativePtr); 1291 } 1292 1293 /** 1294 * If the bitmap's internal config is in one of the public formats, return 1295 * that config, otherwise return null. 1296 */ 1297 public final Config getConfig() { 1298 if (mRecycled) { 1299 Log.w(TAG, "Called getConfig() on a recycle()'d bitmap! This is undefined behavior!"); 1300 } 1301 return Config.nativeToConfig(nativeConfig(mNativePtr)); 1302 } 1303 1304 /** Returns true if the bitmap's config supports per-pixel alpha, and 1305 * if the pixels may contain non-opaque alpha values. For some configs, 1306 * this is always false (e.g. RGB_565), since they do not support per-pixel 1307 * alpha. However, for configs that do, the bitmap may be flagged to be 1308 * known that all of its pixels are opaque. In this case hasAlpha() will 1309 * also return false. If a config such as ARGB_8888 is not so flagged, 1310 * it will return true by default. 1311 */ 1312 public final boolean hasAlpha() { 1313 if (mRecycled) { 1314 Log.w(TAG, "Called hasAlpha() on a recycle()'d bitmap! This is undefined behavior!"); 1315 } 1316 return nativeHasAlpha(mNativePtr); 1317 } 1318 1319 /** 1320 * Tell the bitmap if all of the pixels are known to be opaque (false) 1321 * or if some of the pixels may contain non-opaque alpha values (true). 1322 * Note, for some configs (e.g. RGB_565) this call is ignored, since it 1323 * does not support per-pixel alpha values. 1324 * 1325 * This is meant as a drawing hint, as in some cases a bitmap that is known 1326 * to be opaque can take a faster drawing case than one that may have 1327 * non-opaque per-pixel alpha values. 1328 */ 1329 public void setHasAlpha(boolean hasAlpha) { 1330 checkRecycled("setHasAlpha called on a recycled bitmap"); 1331 nativeSetHasAlpha(mNativePtr, hasAlpha, mRequestPremultiplied); 1332 } 1333 1334 /** 1335 * Indicates whether the renderer responsible for drawing this 1336 * bitmap should attempt to use mipmaps when this bitmap is drawn 1337 * scaled down. 1338 * 1339 * If you know that you are going to draw this bitmap at less than 1340 * 50% of its original size, you may be able to obtain a higher 1341 * quality 1342 * 1343 * This property is only a suggestion that can be ignored by the 1344 * renderer. It is not guaranteed to have any effect. 1345 * 1346 * @return true if the renderer should attempt to use mipmaps, 1347 * false otherwise 1348 * 1349 * @see #setHasMipMap(boolean) 1350 */ 1351 public final boolean hasMipMap() { 1352 if (mRecycled) { 1353 Log.w(TAG, "Called hasMipMap() on a recycle()'d bitmap! This is undefined behavior!"); 1354 } 1355 return nativeHasMipMap(mNativePtr); 1356 } 1357 1358 /** 1359 * Set a hint for the renderer responsible for drawing this bitmap 1360 * indicating that it should attempt to use mipmaps when this bitmap 1361 * is drawn scaled down. 1362 * 1363 * If you know that you are going to draw this bitmap at less than 1364 * 50% of its original size, you may be able to obtain a higher 1365 * quality by turning this property on. 1366 * 1367 * Note that if the renderer respects this hint it might have to 1368 * allocate extra memory to hold the mipmap levels for this bitmap. 1369 * 1370 * This property is only a suggestion that can be ignored by the 1371 * renderer. It is not guaranteed to have any effect. 1372 * 1373 * @param hasMipMap indicates whether the renderer should attempt 1374 * to use mipmaps 1375 * 1376 * @see #hasMipMap() 1377 */ 1378 public final void setHasMipMap(boolean hasMipMap) { 1379 checkRecycled("setHasMipMap called on a recycled bitmap"); 1380 nativeSetHasMipMap(mNativePtr, hasMipMap); 1381 } 1382 1383 /** 1384 * Fills the bitmap's pixels with the specified {@link Color}. 1385 * 1386 * @throws IllegalStateException if the bitmap is not mutable. 1387 */ 1388 public void eraseColor(@ColorInt int c) { 1389 checkRecycled("Can't erase a recycled bitmap"); 1390 if (!isMutable()) { 1391 throw new IllegalStateException("cannot erase immutable bitmaps"); 1392 } 1393 nativeErase(mNativePtr, c); 1394 } 1395 1396 /** 1397 * Returns the {@link Color} at the specified location. Throws an exception 1398 * if x or y are out of bounds (negative or >= to the width or height 1399 * respectively). The returned color is a non-premultiplied ARGB value. 1400 * 1401 * @param x The x coordinate (0...width-1) of the pixel to return 1402 * @param y The y coordinate (0...height-1) of the pixel to return 1403 * @return The argb {@link Color} at the specified coordinate 1404 * @throws IllegalArgumentException if x, y exceed the bitmap's bounds 1405 */ 1406 @ColorInt 1407 public int getPixel(int x, int y) { 1408 checkRecycled("Can't call getPixel() on a recycled bitmap"); 1409 checkPixelAccess(x, y); 1410 return nativeGetPixel(mNativePtr, x, y); 1411 } 1412 1413 /** 1414 * Returns in pixels[] a copy of the data in the bitmap. Each value is 1415 * a packed int representing a {@link Color}. The stride parameter allows 1416 * the caller to allow for gaps in the returned pixels array between 1417 * rows. For normal packed results, just pass width for the stride value. 1418 * The returned colors are non-premultiplied ARGB values. 1419 * 1420 * @param pixels The array to receive the bitmap's colors 1421 * @param offset The first index to write into pixels[] 1422 * @param stride The number of entries in pixels[] to skip between 1423 * rows (must be >= bitmap's width). Can be negative. 1424 * @param x The x coordinate of the first pixel to read from 1425 * the bitmap 1426 * @param y The y coordinate of the first pixel to read from 1427 * the bitmap 1428 * @param width The number of pixels to read from each row 1429 * @param height The number of rows to read 1430 * 1431 * @throws IllegalArgumentException if x, y, width, height exceed the 1432 * bounds of the bitmap, or if abs(stride) < width. 1433 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 1434 * to receive the specified number of pixels. 1435 */ 1436 public void getPixels(@ColorInt int[] pixels, int offset, int stride, 1437 int x, int y, int width, int height) { 1438 checkRecycled("Can't call getPixels() on a recycled bitmap"); 1439 if (width == 0 || height == 0) { 1440 return; // nothing to do 1441 } 1442 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 1443 nativeGetPixels(mNativePtr, pixels, offset, stride, 1444 x, y, width, height); 1445 } 1446 1447 /** 1448 * Shared code to check for illegal arguments passed to getPixel() 1449 * or setPixel() 1450 * 1451 * @param x x coordinate of the pixel 1452 * @param y y coordinate of the pixel 1453 */ 1454 private void checkPixelAccess(int x, int y) { 1455 checkXYSign(x, y); 1456 if (x >= getWidth()) { 1457 throw new IllegalArgumentException("x must be < bitmap.width()"); 1458 } 1459 if (y >= getHeight()) { 1460 throw new IllegalArgumentException("y must be < bitmap.height()"); 1461 } 1462 } 1463 1464 /** 1465 * Shared code to check for illegal arguments passed to getPixels() 1466 * or setPixels() 1467 * 1468 * @param x left edge of the area of pixels to access 1469 * @param y top edge of the area of pixels to access 1470 * @param width width of the area of pixels to access 1471 * @param height height of the area of pixels to access 1472 * @param offset offset into pixels[] array 1473 * @param stride number of elements in pixels[] between each logical row 1474 * @param pixels array to hold the area of pixels being accessed 1475 */ 1476 private void checkPixelsAccess(int x, int y, int width, int height, 1477 int offset, int stride, int pixels[]) { 1478 checkXYSign(x, y); 1479 if (width < 0) { 1480 throw new IllegalArgumentException("width must be >= 0"); 1481 } 1482 if (height < 0) { 1483 throw new IllegalArgumentException("height must be >= 0"); 1484 } 1485 if (x + width > getWidth()) { 1486 throw new IllegalArgumentException( 1487 "x + width must be <= bitmap.width()"); 1488 } 1489 if (y + height > getHeight()) { 1490 throw new IllegalArgumentException( 1491 "y + height must be <= bitmap.height()"); 1492 } 1493 if (Math.abs(stride) < width) { 1494 throw new IllegalArgumentException("abs(stride) must be >= width"); 1495 } 1496 int lastScanline = offset + (height - 1) * stride; 1497 int length = pixels.length; 1498 if (offset < 0 || (offset + width > length) 1499 || lastScanline < 0 1500 || (lastScanline + width > length)) { 1501 throw new ArrayIndexOutOfBoundsException(); 1502 } 1503 } 1504 1505 /** 1506 * <p>Write the specified {@link Color} into the bitmap (assuming it is 1507 * mutable) at the x,y coordinate. The color must be a 1508 * non-premultiplied ARGB value.</p> 1509 * 1510 * @param x The x coordinate of the pixel to replace (0...width-1) 1511 * @param y The y coordinate of the pixel to replace (0...height-1) 1512 * @param color The ARGB color to write into the bitmap 1513 * 1514 * @throws IllegalStateException if the bitmap is not mutable 1515 * @throws IllegalArgumentException if x, y are outside of the bitmap's 1516 * bounds. 1517 */ 1518 public void setPixel(int x, int y, @ColorInt int color) { 1519 checkRecycled("Can't call setPixel() on a recycled bitmap"); 1520 if (!isMutable()) { 1521 throw new IllegalStateException(); 1522 } 1523 checkPixelAccess(x, y); 1524 nativeSetPixel(mNativePtr, x, y, color); 1525 } 1526 1527 /** 1528 * <p>Replace pixels in the bitmap with the colors in the array. Each element 1529 * in the array is a packed int prepresenting a non-premultiplied ARGB 1530 * {@link Color}.</p> 1531 * 1532 * @param pixels The colors to write to the bitmap 1533 * @param offset The index of the first color to read from pixels[] 1534 * @param stride The number of colors in pixels[] to skip between rows. 1535 * Normally this value will be the same as the width of 1536 * the bitmap, but it can be larger (or negative). 1537 * @param x The x coordinate of the first pixel to write to in 1538 * the bitmap. 1539 * @param y The y coordinate of the first pixel to write to in 1540 * the bitmap. 1541 * @param width The number of colors to copy from pixels[] per row 1542 * @param height The number of rows to write to the bitmap 1543 * 1544 * @throws IllegalStateException if the bitmap is not mutable 1545 * @throws IllegalArgumentException if x, y, width, height are outside of 1546 * the bitmap's bounds. 1547 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 1548 * to receive the specified number of pixels. 1549 */ 1550 public void setPixels(@ColorInt int[] pixels, int offset, int stride, 1551 int x, int y, int width, int height) { 1552 checkRecycled("Can't call setPixels() on a recycled bitmap"); 1553 if (!isMutable()) { 1554 throw new IllegalStateException(); 1555 } 1556 if (width == 0 || height == 0) { 1557 return; // nothing to do 1558 } 1559 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 1560 nativeSetPixels(mNativePtr, pixels, offset, stride, 1561 x, y, width, height); 1562 } 1563 1564 public static final Parcelable.Creator<Bitmap> CREATOR 1565 = new Parcelable.Creator<Bitmap>() { 1566 /** 1567 * Rebuilds a bitmap previously stored with writeToParcel(). 1568 * 1569 * @param p Parcel object to read the bitmap from 1570 * @return a new bitmap created from the data in the parcel 1571 */ 1572 public Bitmap createFromParcel(Parcel p) { 1573 Bitmap bm = nativeCreateFromParcel(p); 1574 if (bm == null) { 1575 throw new RuntimeException("Failed to unparcel Bitmap"); 1576 } 1577 return bm; 1578 } 1579 public Bitmap[] newArray(int size) { 1580 return new Bitmap[size]; 1581 } 1582 }; 1583 1584 /** 1585 * No special parcel contents. 1586 */ 1587 public int describeContents() { 1588 return 0; 1589 } 1590 1591 /** 1592 * Write the bitmap and its pixels to the parcel. The bitmap can be 1593 * rebuilt from the parcel by calling CREATOR.createFromParcel(). 1594 * @param p Parcel object to write the bitmap data into 1595 */ 1596 public void writeToParcel(Parcel p, int flags) { 1597 checkRecycled("Can't parcel a recycled bitmap"); 1598 if (!nativeWriteToParcel(mNativePtr, mIsMutable, mDensity, p)) { 1599 throw new RuntimeException("native writeToParcel failed"); 1600 } 1601 } 1602 1603 /** 1604 * Returns a new bitmap that captures the alpha values of the original. 1605 * This may be drawn with Canvas.drawBitmap(), where the color(s) will be 1606 * taken from the paint that is passed to the draw call. 1607 * 1608 * @return new bitmap containing the alpha channel of the original bitmap. 1609 */ 1610 @CheckResult 1611 public Bitmap extractAlpha() { 1612 return extractAlpha(null, null); 1613 } 1614 1615 /** 1616 * Returns a new bitmap that captures the alpha values of the original. 1617 * These values may be affected by the optional Paint parameter, which 1618 * can contain its own alpha, and may also contain a MaskFilter which 1619 * could change the actual dimensions of the resulting bitmap (e.g. 1620 * a blur maskfilter might enlarge the resulting bitmap). If offsetXY 1621 * is not null, it returns the amount to offset the returned bitmap so 1622 * that it will logically align with the original. For example, if the 1623 * paint contains a blur of radius 2, then offsetXY[] would contains 1624 * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then 1625 * drawing the original would result in the blur visually aligning with 1626 * the original. 1627 * 1628 * <p>The initial density of the returned bitmap is the same as the original's. 1629 * 1630 * @param paint Optional paint used to modify the alpha values in the 1631 * resulting bitmap. Pass null for default behavior. 1632 * @param offsetXY Optional array that returns the X (index 0) and Y 1633 * (index 1) offset needed to position the returned bitmap 1634 * so that it visually lines up with the original. 1635 * @return new bitmap containing the (optionally modified by paint) alpha 1636 * channel of the original bitmap. This may be drawn with 1637 * Canvas.drawBitmap(), where the color(s) will be taken from the 1638 * paint that is passed to the draw call. 1639 */ 1640 @CheckResult 1641 public Bitmap extractAlpha(Paint paint, int[] offsetXY) { 1642 checkRecycled("Can't extractAlpha on a recycled bitmap"); 1643 long nativePaint = paint != null ? paint.getNativeInstance() : 0; 1644 Bitmap bm = nativeExtractAlpha(mNativePtr, nativePaint, offsetXY); 1645 if (bm == null) { 1646 throw new RuntimeException("Failed to extractAlpha on Bitmap"); 1647 } 1648 bm.mDensity = mDensity; 1649 return bm; 1650 } 1651 1652 /** 1653 * Given another bitmap, return true if it has the same dimensions, config, 1654 * and pixel data as this bitmap. If any of those differ, return false. 1655 * If other is null, return false. 1656 */ 1657 public boolean sameAs(Bitmap other) { 1658 checkRecycled("Can't call sameAs on a recycled bitmap!"); 1659 if (this == other) return true; 1660 if (other == null) return false; 1661 if (other.isRecycled()) { 1662 throw new IllegalArgumentException("Can't compare to a recycled bitmap!"); 1663 } 1664 return nativeSameAs(mNativePtr, other.mNativePtr); 1665 } 1666 1667 /** 1668 * Rebuilds any caches associated with the bitmap that are used for 1669 * drawing it. In the case of purgeable bitmaps, this call will attempt to 1670 * ensure that the pixels have been decoded. 1671 * If this is called on more than one bitmap in sequence, the priority is 1672 * given in LRU order (i.e. the last bitmap called will be given highest 1673 * priority). 1674 * 1675 * For bitmaps with no associated caches, this call is effectively a no-op, 1676 * and therefore is harmless. 1677 */ 1678 public void prepareToDraw() { 1679 checkRecycled("Can't prepareToDraw on a recycled bitmap!"); 1680 // Kick off an update/upload of the bitmap outside of the normal 1681 // draw path. 1682 nativePrepareToDraw(mNativePtr); 1683 } 1684 1685 //////////// native methods 1686 1687 private static native Bitmap nativeCreate(int[] colors, int offset, 1688 int stride, int width, int height, 1689 int nativeConfig, boolean mutable); 1690 private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig, 1691 boolean isMutable); 1692 private static native Bitmap nativeCopyAshmem(long nativeSrcBitmap); 1693 private static native Bitmap nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig); 1694 private static native long nativeGetNativeFinalizer(); 1695 private static native boolean nativeRecycle(long nativeBitmap); 1696 private static native void nativeReconfigure(long nativeBitmap, int width, int height, 1697 int config, boolean isPremultiplied); 1698 1699 private static native boolean nativeCompress(long nativeBitmap, int format, 1700 int quality, OutputStream stream, 1701 byte[] tempStorage); 1702 private static native void nativeErase(long nativeBitmap, int color); 1703 private static native int nativeRowBytes(long nativeBitmap); 1704 private static native int nativeConfig(long nativeBitmap); 1705 1706 private static native int nativeGetPixel(long nativeBitmap, int x, int y); 1707 private static native void nativeGetPixels(long nativeBitmap, int[] pixels, 1708 int offset, int stride, int x, int y, 1709 int width, int height); 1710 1711 private static native void nativeSetPixel(long nativeBitmap, int x, int y, int color); 1712 private static native void nativeSetPixels(long nativeBitmap, int[] colors, 1713 int offset, int stride, int x, int y, 1714 int width, int height); 1715 private static native void nativeCopyPixelsToBuffer(long nativeBitmap, 1716 Buffer dst); 1717 private static native void nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src); 1718 private static native int nativeGenerationId(long nativeBitmap); 1719 1720 private static native Bitmap nativeCreateFromParcel(Parcel p); 1721 // returns true on success 1722 private static native boolean nativeWriteToParcel(long nativeBitmap, 1723 boolean isMutable, 1724 int density, 1725 Parcel p); 1726 // returns a new bitmap built from the native bitmap's alpha, and the paint 1727 private static native Bitmap nativeExtractAlpha(long nativeBitmap, 1728 long nativePaint, 1729 int[] offsetXY); 1730 1731 private static native boolean nativeHasAlpha(long nativeBitmap); 1732 private static native boolean nativeIsPremultiplied(long nativeBitmap); 1733 private static native void nativeSetPremultiplied(long nativeBitmap, 1734 boolean isPremul); 1735 private static native void nativeSetHasAlpha(long nativeBitmap, 1736 boolean hasAlpha, 1737 boolean requestPremul); 1738 private static native boolean nativeHasMipMap(long nativeBitmap); 1739 private static native void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap); 1740 private static native boolean nativeSameAs(long nativeBitmap0, long nativeBitmap1); 1741 private static native void nativePrepareToDraw(long nativeBitmap); 1742 private static native int nativeGetAllocationByteCount(long nativeBitmap); 1743} 1744