Bitmap.java revision 9192d5e8d78b826a665ce048c007e6eaf0f5b003
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 final int nativeInt; 469 470 private static Config sConfigs[] = { 471 null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888 472 }; 473 474 Config(int ni) { 475 this.nativeInt = ni; 476 } 477 478 static Config nativeToConfig(int ni) { 479 return sConfigs[ni]; 480 } 481 } 482 483 /** 484 * <p>Copy the bitmap's pixels into the specified buffer (allocated by the 485 * caller). An exception is thrown if the buffer is not large enough to 486 * hold all of the pixels (taking into account the number of bytes per 487 * pixel) or if the Buffer subclass is not one of the support types 488 * (ByteBuffer, ShortBuffer, IntBuffer).</p> 489 * <p>The content of the bitmap is copied into the buffer as-is. This means 490 * that if this bitmap stores its pixels pre-multiplied 491 * (see {@link #isPremultiplied()}, the values in the buffer will also be 492 * pre-multiplied.</p> 493 * <p>After this method returns, the current position of the buffer is 494 * updated: the position is incremented by the number of elements written 495 * in the buffer.</p> 496 */ 497 public void copyPixelsToBuffer(Buffer dst) { 498 int elements = dst.remaining(); 499 int shift; 500 if (dst instanceof ByteBuffer) { 501 shift = 0; 502 } else if (dst instanceof ShortBuffer) { 503 shift = 1; 504 } else if (dst instanceof IntBuffer) { 505 shift = 2; 506 } else { 507 throw new RuntimeException("unsupported Buffer subclass"); 508 } 509 510 long bufferSize = (long)elements << shift; 511 long pixelSize = getByteCount(); 512 513 if (bufferSize < pixelSize) { 514 throw new RuntimeException("Buffer not large enough for pixels"); 515 } 516 517 nativeCopyPixelsToBuffer(mNativePtr, dst); 518 519 // now update the buffer's position 520 int position = dst.position(); 521 position += pixelSize >> shift; 522 dst.position(position); 523 } 524 525 /** 526 * <p>Copy the pixels from the buffer, beginning at the current position, 527 * overwriting the bitmap's pixels. The data in the buffer is not changed 528 * in any way (unlike setPixels(), which converts from unpremultipled 32bit 529 * to whatever the bitmap's native format is.</p> 530 * <p>After this method returns, the current position of the buffer is 531 * updated: the position is incremented by the number of elements read from 532 * the buffer. If you need to read the bitmap from the buffer again you must 533 * first rewind the buffer.</p> 534 */ 535 public void copyPixelsFromBuffer(Buffer src) { 536 checkRecycled("copyPixelsFromBuffer called on recycled bitmap"); 537 538 int elements = src.remaining(); 539 int shift; 540 if (src instanceof ByteBuffer) { 541 shift = 0; 542 } else if (src instanceof ShortBuffer) { 543 shift = 1; 544 } else if (src instanceof IntBuffer) { 545 shift = 2; 546 } else { 547 throw new RuntimeException("unsupported Buffer subclass"); 548 } 549 550 long bufferBytes = (long) elements << shift; 551 long bitmapBytes = getByteCount(); 552 553 if (bufferBytes < bitmapBytes) { 554 throw new RuntimeException("Buffer not large enough for pixels"); 555 } 556 557 nativeCopyPixelsFromBuffer(mNativePtr, src); 558 559 // now update the buffer's position 560 int position = src.position(); 561 position += bitmapBytes >> shift; 562 src.position(position); 563 } 564 565 /** 566 * Tries to make a new bitmap based on the dimensions of this bitmap, 567 * setting the new bitmap's config to the one specified, and then copying 568 * this bitmap's pixels into the new bitmap. If the conversion is not 569 * supported, or the allocator fails, then this returns NULL. The returned 570 * bitmap initially has the same density as the original. 571 * 572 * @param config The desired config for the resulting bitmap 573 * @param isMutable True if the resulting bitmap should be mutable (i.e. 574 * its pixels can be modified) 575 * @return the new bitmap, or null if the copy could not be made. 576 */ 577 public Bitmap copy(Config config, boolean isMutable) { 578 checkRecycled("Can't copy a recycled bitmap"); 579 Bitmap b = nativeCopy(mNativePtr, config.nativeInt, isMutable); 580 if (b != null) { 581 b.setPremultiplied(mRequestPremultiplied); 582 b.mDensity = mDensity; 583 } 584 return b; 585 } 586 587 /** 588 * Creates a new immutable bitmap backed by ashmem which can efficiently 589 * be passed between processes. 590 * 591 * @hide 592 */ 593 public Bitmap createAshmemBitmap() { 594 checkRecycled("Can't copy a recycled bitmap"); 595 Bitmap b = nativeCopyAshmem(mNativePtr); 596 if (b != null) { 597 b.setPremultiplied(mRequestPremultiplied); 598 b.mDensity = mDensity; 599 } 600 return b; 601 } 602 603 /** 604 * Creates a new immutable bitmap backed by ashmem which can efficiently 605 * be passed between processes. 606 * 607 * @hide 608 */ 609 public Bitmap createAshmemBitmap(Config config) { 610 checkRecycled("Can't copy a recycled bitmap"); 611 Bitmap b = nativeCopyAshmemConfig(mNativePtr, config.nativeInt); 612 if (b != null) { 613 b.setPremultiplied(mRequestPremultiplied); 614 b.mDensity = mDensity; 615 } 616 return b; 617 } 618 619 /** 620 * Creates a new bitmap, scaled from an existing bitmap, when possible. If the 621 * specified width and height are the same as the current width and height of 622 * the source bitmap, the source bitmap is returned and no new bitmap is 623 * created. 624 * 625 * @param src The source bitmap. 626 * @param dstWidth The new bitmap's desired width. 627 * @param dstHeight The new bitmap's desired height. 628 * @param filter true if the source should be filtered. 629 * @return The new scaled bitmap or the source bitmap if no scaling is required. 630 * @throws IllegalArgumentException if width is <= 0, or height is <= 0 631 */ 632 public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, 633 boolean filter) { 634 Matrix m; 635 synchronized (Bitmap.class) { 636 // small pool of just 1 matrix 637 m = sScaleMatrix; 638 sScaleMatrix = null; 639 } 640 641 if (m == null) { 642 m = new Matrix(); 643 } 644 645 final int width = src.getWidth(); 646 final int height = src.getHeight(); 647 final float sx = dstWidth / (float)width; 648 final float sy = dstHeight / (float)height; 649 m.setScale(sx, sy); 650 Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter); 651 652 synchronized (Bitmap.class) { 653 // do we need to check for null? why not just assign everytime? 654 if (sScaleMatrix == null) { 655 sScaleMatrix = m; 656 } 657 } 658 659 return b; 660 } 661 662 /** 663 * Returns an immutable bitmap from the source bitmap. The new bitmap may 664 * be the same object as source, or a copy may have been made. It is 665 * initialized with the same density as the original bitmap. 666 */ 667 public static Bitmap createBitmap(Bitmap src) { 668 return createBitmap(src, 0, 0, src.getWidth(), src.getHeight()); 669 } 670 671 /** 672 * Returns an immutable bitmap from the specified subset of the source 673 * bitmap. The new bitmap may be the same object as source, or a copy may 674 * have been made. It is initialized with the same density as the original 675 * bitmap. 676 * 677 * @param source The bitmap we are subsetting 678 * @param x The x coordinate of the first pixel in source 679 * @param y The y coordinate of the first pixel in source 680 * @param width The number of pixels in each row 681 * @param height The number of rows 682 * @return A copy of a subset of the source bitmap or the source bitmap itself. 683 * @throws IllegalArgumentException if the x, y, width, height values are 684 * outside of the dimensions of the source bitmap, or width is <= 0, 685 * or height is <= 0 686 */ 687 public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) { 688 return createBitmap(source, x, y, width, height, null, false); 689 } 690 691 /** 692 * Returns an immutable bitmap from subset of the source bitmap, 693 * transformed by the optional matrix. The new bitmap may be the 694 * same object as source, or a copy may have been made. It is 695 * initialized with the same density as the original bitmap. 696 * 697 * If the source bitmap is immutable and the requested subset is the 698 * same as the source bitmap itself, then the source bitmap is 699 * returned and no new bitmap is created. 700 * 701 * @param source The bitmap we are subsetting 702 * @param x The x coordinate of the first pixel in source 703 * @param y The y coordinate of the first pixel in source 704 * @param width The number of pixels in each row 705 * @param height The number of rows 706 * @param m Optional matrix to be applied to the pixels 707 * @param filter true if the source should be filtered. 708 * Only applies if the matrix contains more than just 709 * translation. 710 * @return A bitmap that represents the specified subset of source 711 * @throws IllegalArgumentException if the x, y, width, height values are 712 * outside of the dimensions of the source bitmap, or width is <= 0, 713 * or height is <= 0 714 */ 715 public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, 716 Matrix m, boolean filter) { 717 718 checkXYSign(x, y); 719 checkWidthHeight(width, height); 720 if (x + width > source.getWidth()) { 721 throw new IllegalArgumentException("x + width must be <= bitmap.width()"); 722 } 723 if (y + height > source.getHeight()) { 724 throw new IllegalArgumentException("y + height must be <= bitmap.height()"); 725 } 726 727 // check if we can just return our argument unchanged 728 if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() && 729 height == source.getHeight() && (m == null || m.isIdentity())) { 730 return source; 731 } 732 733 int neww = width; 734 int newh = height; 735 Canvas canvas = new Canvas(); 736 Bitmap bitmap; 737 Paint paint; 738 739 Rect srcR = new Rect(x, y, x + width, y + height); 740 RectF dstR = new RectF(0, 0, width, height); 741 742 Config newConfig = Config.ARGB_8888; 743 final Config config = source.getConfig(); 744 // GIF files generate null configs, assume ARGB_8888 745 if (config != null) { 746 switch (config) { 747 case RGB_565: 748 newConfig = Config.RGB_565; 749 break; 750 case ALPHA_8: 751 newConfig = Config.ALPHA_8; 752 break; 753 //noinspection deprecation 754 case ARGB_4444: 755 case ARGB_8888: 756 default: 757 newConfig = Config.ARGB_8888; 758 break; 759 } 760 } 761 762 if (m == null || m.isIdentity()) { 763 bitmap = createBitmap(neww, newh, newConfig, source.hasAlpha()); 764 paint = null; // not needed 765 } else { 766 final boolean transformed = !m.rectStaysRect(); 767 768 RectF deviceR = new RectF(); 769 m.mapRect(deviceR, dstR); 770 771 neww = Math.round(deviceR.width()); 772 newh = Math.round(deviceR.height()); 773 774 bitmap = createBitmap(neww, newh, transformed ? Config.ARGB_8888 : newConfig, 775 transformed || source.hasAlpha()); 776 777 canvas.translate(-deviceR.left, -deviceR.top); 778 canvas.concat(m); 779 780 paint = new Paint(); 781 paint.setFilterBitmap(filter); 782 if (transformed) { 783 paint.setAntiAlias(true); 784 } 785 } 786 787 // The new bitmap was created from a known bitmap source so assume that 788 // they use the same density 789 bitmap.mDensity = source.mDensity; 790 bitmap.setHasAlpha(source.hasAlpha()); 791 bitmap.setPremultiplied(source.mRequestPremultiplied); 792 793 canvas.setBitmap(bitmap); 794 canvas.drawBitmap(source, srcR, dstR, paint); 795 canvas.setBitmap(null); 796 797 return bitmap; 798 } 799 800 /** 801 * Returns a mutable bitmap with the specified width and height. Its 802 * initial density is as per {@link #getDensity}. 803 * 804 * @param width The width of the bitmap 805 * @param height The height of the bitmap 806 * @param config The bitmap config to create. 807 * @throws IllegalArgumentException if the width or height are <= 0 808 */ 809 public static Bitmap createBitmap(int width, int height, Config config) { 810 return createBitmap(width, height, config, true); 811 } 812 813 /** 814 * Returns a mutable bitmap with the specified width and height. Its 815 * initial density is determined from the given {@link DisplayMetrics}. 816 * 817 * @param display Display metrics for the display this bitmap will be 818 * drawn on. 819 * @param width The width of the bitmap 820 * @param height The height of the bitmap 821 * @param config The bitmap config to create. 822 * @throws IllegalArgumentException if the width or height are <= 0 823 */ 824 public static Bitmap createBitmap(DisplayMetrics display, int width, 825 int height, Config config) { 826 return createBitmap(display, width, height, config, true); 827 } 828 829 /** 830 * Returns a mutable bitmap with the specified width and height. Its 831 * initial density is as per {@link #getDensity}. 832 * 833 * @param width The width of the bitmap 834 * @param height The height of the bitmap 835 * @param config The bitmap config to create. 836 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the 837 * bitmap as opaque. Doing so will clear the bitmap in black 838 * instead of transparent. 839 * 840 * @throws IllegalArgumentException if the width or height are <= 0 841 */ 842 private static Bitmap createBitmap(int width, int height, Config config, boolean hasAlpha) { 843 return createBitmap(null, width, height, config, hasAlpha); 844 } 845 846 /** 847 * Returns a mutable bitmap with the specified width and height. Its 848 * initial density is determined from the given {@link DisplayMetrics}. 849 * 850 * @param display Display metrics for the display this bitmap will be 851 * drawn on. 852 * @param width The width of the bitmap 853 * @param height The height of the bitmap 854 * @param config The bitmap config to create. 855 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the 856 * bitmap as opaque. Doing so will clear the bitmap in black 857 * instead of transparent. 858 * 859 * @throws IllegalArgumentException if the width or height are <= 0 860 */ 861 private static Bitmap createBitmap(DisplayMetrics display, int width, int height, 862 Config config, boolean hasAlpha) { 863 if (width <= 0 || height <= 0) { 864 throw new IllegalArgumentException("width and height must be > 0"); 865 } 866 Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true); 867 if (display != null) { 868 bm.mDensity = display.densityDpi; 869 } 870 bm.setHasAlpha(hasAlpha); 871 if (config == Config.ARGB_8888 && !hasAlpha) { 872 nativeErase(bm.mNativePtr, 0xff000000); 873 } 874 // No need to initialize the bitmap to zeroes with other configs; 875 // it is backed by a VM byte array which is by definition preinitialized 876 // to all zeroes. 877 return bm; 878 } 879 880 /** 881 * Returns a immutable bitmap with the specified width and height, with each 882 * pixel value set to the corresponding value in the colors array. Its 883 * initial density is as per {@link #getDensity}. 884 * 885 * @param colors Array of {@link Color} used to initialize the pixels. 886 * @param offset Number of values to skip before the first color in the 887 * array of colors. 888 * @param stride Number of colors in the array between rows (must be >= 889 * width or <= -width). 890 * @param width The width of the bitmap 891 * @param height The height of the bitmap 892 * @param config The bitmap config to create. If the config does not 893 * support per-pixel alpha (e.g. RGB_565), then the alpha 894 * bytes in the colors[] will be ignored (assumed to be FF) 895 * @throws IllegalArgumentException if the width or height are <= 0, or if 896 * the color array's length is less than the number of pixels. 897 */ 898 public static Bitmap createBitmap(int colors[], int offset, int stride, 899 int width, int height, Config config) { 900 return createBitmap(null, colors, offset, stride, width, height, config); 901 } 902 903 /** 904 * Returns a immutable bitmap with the specified width and height, with each 905 * pixel value set to the corresponding value in the colors array. Its 906 * initial density is determined from the given {@link DisplayMetrics}. 907 * 908 * @param display Display metrics for the display this bitmap will be 909 * drawn on. 910 * @param colors Array of {@link Color} used to initialize the pixels. 911 * @param offset Number of values to skip before the first color in the 912 * array of colors. 913 * @param stride Number of colors in the array between rows (must be >= 914 * width or <= -width). 915 * @param width The width of the bitmap 916 * @param height The height of the bitmap 917 * @param config The bitmap config to create. If the config does not 918 * support per-pixel alpha (e.g. RGB_565), then the alpha 919 * bytes in the colors[] will be ignored (assumed to be FF) 920 * @throws IllegalArgumentException if the width or height are <= 0, or if 921 * the color array's length is less than the number of pixels. 922 */ 923 public static Bitmap createBitmap(DisplayMetrics display, int colors[], 924 int offset, int stride, int width, int height, Config config) { 925 926 checkWidthHeight(width, height); 927 if (Math.abs(stride) < width) { 928 throw new IllegalArgumentException("abs(stride) must be >= width"); 929 } 930 int lastScanline = offset + (height - 1) * stride; 931 int length = colors.length; 932 if (offset < 0 || (offset + width > length) || lastScanline < 0 || 933 (lastScanline + width > length)) { 934 throw new ArrayIndexOutOfBoundsException(); 935 } 936 if (width <= 0 || height <= 0) { 937 throw new IllegalArgumentException("width and height must be > 0"); 938 } 939 Bitmap bm = nativeCreate(colors, offset, stride, width, height, 940 config.nativeInt, false); 941 if (display != null) { 942 bm.mDensity = display.densityDpi; 943 } 944 return bm; 945 } 946 947 /** 948 * Returns a immutable bitmap with the specified width and height, with each 949 * pixel value set to the corresponding value in the colors array. Its 950 * initial density is as per {@link #getDensity}. 951 * 952 * @param colors Array of {@link Color} used to initialize the pixels. 953 * This array must be at least as large as width * height. 954 * @param width The width of the bitmap 955 * @param height The height of the bitmap 956 * @param config The bitmap config to create. If the config does not 957 * support per-pixel alpha (e.g. RGB_565), then the alpha 958 * bytes in the colors[] will be ignored (assumed to be FF) 959 * @throws IllegalArgumentException if the width or height are <= 0, or if 960 * the color array's length is less than the number of pixels. 961 */ 962 public static Bitmap createBitmap(int colors[], int width, int height, Config config) { 963 return createBitmap(null, colors, 0, width, width, height, config); 964 } 965 966 /** 967 * Returns a immutable bitmap with the specified width and height, with each 968 * pixel value set to the corresponding value in the colors array. Its 969 * initial density is determined from the given {@link DisplayMetrics}. 970 * 971 * @param display Display metrics for the display this bitmap will be 972 * drawn on. 973 * @param colors Array of {@link Color} used to initialize the pixels. 974 * This array must be at least as large as width * height. 975 * @param width The width of the bitmap 976 * @param height The height of the bitmap 977 * @param config The bitmap config to create. If the config does not 978 * support per-pixel alpha (e.g. RGB_565), then the alpha 979 * bytes in the colors[] will be ignored (assumed to be FF) 980 * @throws IllegalArgumentException if the width or height are <= 0, or if 981 * the color array's length is less than the number of pixels. 982 */ 983 public static Bitmap createBitmap(DisplayMetrics display, int colors[], 984 int width, int height, Config config) { 985 return createBitmap(display, colors, 0, width, width, height, config); 986 } 987 988 /** 989 * Returns an optional array of private data, used by the UI system for 990 * some bitmaps. Not intended to be called by applications. 991 */ 992 public byte[] getNinePatchChunk() { 993 return mNinePatchChunk; 994 } 995 996 /** 997 * Populates a rectangle with the bitmap's optical insets. 998 * 999 * @param outInsets Rect to populate with optical insets 1000 * @hide 1001 */ 1002 public void getOpticalInsets(@NonNull Rect outInsets) { 1003 if (mNinePatchInsets == null) { 1004 outInsets.setEmpty(); 1005 } else { 1006 outInsets.set(mNinePatchInsets.opticalRect); 1007 } 1008 } 1009 1010 /** @hide */ 1011 public NinePatch.InsetStruct getNinePatchInsets() { 1012 return mNinePatchInsets; 1013 } 1014 1015 /** 1016 * Specifies the known formats a bitmap can be compressed into 1017 */ 1018 public enum CompressFormat { 1019 JPEG (0), 1020 PNG (1), 1021 WEBP (2); 1022 1023 CompressFormat(int nativeInt) { 1024 this.nativeInt = nativeInt; 1025 } 1026 final int nativeInt; 1027 } 1028 1029 /** 1030 * Number of bytes of temp storage we use for communicating between the 1031 * native compressor and the java OutputStream. 1032 */ 1033 private final static int WORKING_COMPRESS_STORAGE = 4096; 1034 1035 /** 1036 * Write a compressed version of the bitmap to the specified outputstream. 1037 * If this returns true, the bitmap can be reconstructed by passing a 1038 * corresponding inputstream to BitmapFactory.decodeStream(). Note: not 1039 * all Formats support all bitmap configs directly, so it is possible that 1040 * the returned bitmap from BitmapFactory could be in a different bitdepth, 1041 * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque 1042 * pixels). 1043 * 1044 * @param format The format of the compressed image 1045 * @param quality Hint to the compressor, 0-100. 0 meaning compress for 1046 * small size, 100 meaning compress for max quality. Some 1047 * formats, like PNG which is lossless, will ignore the 1048 * quality setting 1049 * @param stream The outputstream to write the compressed data. 1050 * @return true if successfully compressed to the specified stream. 1051 */ 1052 public boolean compress(CompressFormat format, int quality, OutputStream stream) { 1053 checkRecycled("Can't compress a recycled bitmap"); 1054 // do explicit check before calling the native method 1055 if (stream == null) { 1056 throw new NullPointerException(); 1057 } 1058 if (quality < 0 || quality > 100) { 1059 throw new IllegalArgumentException("quality must be 0..100"); 1060 } 1061 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress"); 1062 boolean result = nativeCompress(mNativePtr, format.nativeInt, 1063 quality, stream, new byte[WORKING_COMPRESS_STORAGE]); 1064 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 1065 return result; 1066 } 1067 1068 /** 1069 * Returns true if the bitmap is marked as mutable (i.e. can be drawn into) 1070 */ 1071 public final boolean isMutable() { 1072 return mIsMutable; 1073 } 1074 1075 /** 1076 * <p>Indicates whether pixels stored in this bitmaps are stored pre-multiplied. 1077 * When a pixel is pre-multiplied, the RGB components have been multiplied by 1078 * the alpha component. For instance, if the original color is a 50% 1079 * translucent red <code>(128, 255, 0, 0)</code>, the pre-multiplied form is 1080 * <code>(128, 128, 0, 0)</code>.</p> 1081 * 1082 * <p>This method always returns false if {@link #getConfig()} is 1083 * {@link Bitmap.Config#RGB_565}.</p> 1084 * 1085 * <p>The return value is undefined if {@link #getConfig()} is 1086 * {@link Bitmap.Config#ALPHA_8}.</p> 1087 * 1088 * <p>This method only returns true if {@link #hasAlpha()} returns true. 1089 * A bitmap with no alpha channel can be used both as a pre-multiplied and 1090 * as a non pre-multiplied bitmap.</p> 1091 * 1092 * <p>Only pre-multiplied bitmaps may be drawn by the view system or 1093 * {@link Canvas}. If a non-pre-multiplied bitmap with an alpha channel is 1094 * drawn to a Canvas, a RuntimeException will be thrown.</p> 1095 * 1096 * @return true if the underlying pixels have been pre-multiplied, false 1097 * otherwise 1098 * 1099 * @see Bitmap#setPremultiplied(boolean) 1100 * @see BitmapFactory.Options#inPremultiplied 1101 */ 1102 public final boolean isPremultiplied() { 1103 if (mRecycled) { 1104 Log.w(TAG, "Called isPremultiplied() on a recycle()'d bitmap! This is undefined behavior!"); 1105 } 1106 return nativeIsPremultiplied(mNativePtr); 1107 } 1108 1109 /** 1110 * Sets whether the bitmap should treat its data as pre-multiplied. 1111 * 1112 * <p>Bitmaps are always treated as pre-multiplied by the view system and 1113 * {@link Canvas} for performance reasons. Storing un-pre-multiplied data in 1114 * a Bitmap (through {@link #setPixel}, {@link #setPixels}, or {@link 1115 * BitmapFactory.Options#inPremultiplied BitmapFactory.Options.inPremultiplied}) 1116 * can lead to incorrect blending if drawn by the framework.</p> 1117 * 1118 * <p>This method will not affect the behavior of a bitmap without an alpha 1119 * channel, or if {@link #hasAlpha()} returns false.</p> 1120 * 1121 * <p>Calling {@link #createBitmap} or {@link #createScaledBitmap} with a source 1122 * Bitmap whose colors are not pre-multiplied may result in a RuntimeException, 1123 * since those functions require drawing the source, which is not supported for 1124 * un-pre-multiplied Bitmaps.</p> 1125 * 1126 * @see Bitmap#isPremultiplied() 1127 * @see BitmapFactory.Options#inPremultiplied 1128 */ 1129 public final void setPremultiplied(boolean premultiplied) { 1130 checkRecycled("setPremultiplied called on a recycled bitmap"); 1131 mRequestPremultiplied = premultiplied; 1132 nativeSetPremultiplied(mNativePtr, premultiplied); 1133 } 1134 1135 /** Returns the bitmap's width */ 1136 public final int getWidth() { 1137 if (mRecycled) { 1138 Log.w(TAG, "Called getWidth() on a recycle()'d bitmap! This is undefined behavior!"); 1139 } 1140 return mWidth; 1141 } 1142 1143 /** Returns the bitmap's height */ 1144 public final int getHeight() { 1145 if (mRecycled) { 1146 Log.w(TAG, "Called getHeight() on a recycle()'d bitmap! This is undefined behavior!"); 1147 } 1148 return mHeight; 1149 } 1150 1151 /** 1152 * Convenience for calling {@link #getScaledWidth(int)} with the target 1153 * density of the given {@link Canvas}. 1154 */ 1155 public int getScaledWidth(Canvas canvas) { 1156 return scaleFromDensity(getWidth(), mDensity, canvas.mDensity); 1157 } 1158 1159 /** 1160 * Convenience for calling {@link #getScaledHeight(int)} with the target 1161 * density of the given {@link Canvas}. 1162 */ 1163 public int getScaledHeight(Canvas canvas) { 1164 return scaleFromDensity(getHeight(), mDensity, canvas.mDensity); 1165 } 1166 1167 /** 1168 * Convenience for calling {@link #getScaledWidth(int)} with the target 1169 * density of the given {@link DisplayMetrics}. 1170 */ 1171 public int getScaledWidth(DisplayMetrics metrics) { 1172 return scaleFromDensity(getWidth(), mDensity, metrics.densityDpi); 1173 } 1174 1175 /** 1176 * Convenience for calling {@link #getScaledHeight(int)} with the target 1177 * density of the given {@link DisplayMetrics}. 1178 */ 1179 public int getScaledHeight(DisplayMetrics metrics) { 1180 return scaleFromDensity(getHeight(), mDensity, metrics.densityDpi); 1181 } 1182 1183 /** 1184 * Convenience method that returns the width of this bitmap divided 1185 * by the density scale factor. 1186 * 1187 * @param targetDensity The density of the target canvas of the bitmap. 1188 * @return The scaled width of this bitmap, according to the density scale factor. 1189 */ 1190 public int getScaledWidth(int targetDensity) { 1191 return scaleFromDensity(getWidth(), mDensity, targetDensity); 1192 } 1193 1194 /** 1195 * Convenience method that returns the height of this bitmap divided 1196 * by the density scale factor. 1197 * 1198 * @param targetDensity The density of the target canvas of the bitmap. 1199 * @return The scaled height of this bitmap, according to the density scale factor. 1200 */ 1201 public int getScaledHeight(int targetDensity) { 1202 return scaleFromDensity(getHeight(), mDensity, targetDensity); 1203 } 1204 1205 /** 1206 * @hide 1207 */ 1208 static public int scaleFromDensity(int size, int sdensity, int tdensity) { 1209 if (sdensity == DENSITY_NONE || tdensity == DENSITY_NONE || sdensity == tdensity) { 1210 return size; 1211 } 1212 1213 // Scale by tdensity / sdensity, rounding up. 1214 return ((size * tdensity) + (sdensity >> 1)) / sdensity; 1215 } 1216 1217 /** 1218 * Return the number of bytes between rows in the bitmap's pixels. Note that 1219 * this refers to the pixels as stored natively by the bitmap. If you call 1220 * getPixels() or setPixels(), then the pixels are uniformly treated as 1221 * 32bit values, packed according to the Color class. 1222 * 1223 * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, this method 1224 * should not be used to calculate the memory usage of the bitmap. Instead, 1225 * see {@link #getAllocationByteCount()}. 1226 * 1227 * @return number of bytes between rows of the native bitmap pixels. 1228 */ 1229 public final int getRowBytes() { 1230 if (mRecycled) { 1231 Log.w(TAG, "Called getRowBytes() on a recycle()'d bitmap! This is undefined behavior!"); 1232 } 1233 return nativeRowBytes(mNativePtr); 1234 } 1235 1236 /** 1237 * Returns the minimum number of bytes that can be used to store this bitmap's pixels. 1238 * 1239 * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can 1240 * no longer be used to determine memory usage of a bitmap. See {@link 1241 * #getAllocationByteCount()}.</p> 1242 */ 1243 public final int getByteCount() { 1244 // int result permits bitmaps up to 46,340 x 46,340 1245 return getRowBytes() * getHeight(); 1246 } 1247 1248 /** 1249 * Returns the size of the allocated memory used to store this bitmap's pixels. 1250 * 1251 * <p>This can be larger than the result of {@link #getByteCount()} if a bitmap is reused to 1252 * decode other bitmaps of smaller size, or by manual reconfiguration. See {@link 1253 * #reconfigure(int, int, Config)}, {@link #setWidth(int)}, {@link #setHeight(int)}, {@link 1254 * #setConfig(Bitmap.Config)}, and {@link BitmapFactory.Options#inBitmap 1255 * BitmapFactory.Options.inBitmap}. If a bitmap is not modified in this way, this value will be 1256 * the same as that returned by {@link #getByteCount()}.</p> 1257 * 1258 * <p>This value will not change over the lifetime of a Bitmap.</p> 1259 * 1260 * @see #reconfigure(int, int, Config) 1261 */ 1262 public final int getAllocationByteCount() { 1263 return nativeGetAllocationByteCount(mNativePtr); 1264 } 1265 1266 /** 1267 * If the bitmap's internal config is in one of the public formats, return 1268 * that config, otherwise return null. 1269 */ 1270 public final Config getConfig() { 1271 if (mRecycled) { 1272 Log.w(TAG, "Called getConfig() on a recycle()'d bitmap! This is undefined behavior!"); 1273 } 1274 return Config.nativeToConfig(nativeConfig(mNativePtr)); 1275 } 1276 1277 /** Returns true if the bitmap's config supports per-pixel alpha, and 1278 * if the pixels may contain non-opaque alpha values. For some configs, 1279 * this is always false (e.g. RGB_565), since they do not support per-pixel 1280 * alpha. However, for configs that do, the bitmap may be flagged to be 1281 * known that all of its pixels are opaque. In this case hasAlpha() will 1282 * also return false. If a config such as ARGB_8888 is not so flagged, 1283 * it will return true by default. 1284 */ 1285 public final boolean hasAlpha() { 1286 if (mRecycled) { 1287 Log.w(TAG, "Called hasAlpha() on a recycle()'d bitmap! This is undefined behavior!"); 1288 } 1289 return nativeHasAlpha(mNativePtr); 1290 } 1291 1292 /** 1293 * Tell the bitmap if all of the pixels are known to be opaque (false) 1294 * or if some of the pixels may contain non-opaque alpha values (true). 1295 * Note, for some configs (e.g. RGB_565) this call is ignored, since it 1296 * does not support per-pixel alpha values. 1297 * 1298 * This is meant as a drawing hint, as in some cases a bitmap that is known 1299 * to be opaque can take a faster drawing case than one that may have 1300 * non-opaque per-pixel alpha values. 1301 */ 1302 public void setHasAlpha(boolean hasAlpha) { 1303 checkRecycled("setHasAlpha called on a recycled bitmap"); 1304 nativeSetHasAlpha(mNativePtr, hasAlpha, mRequestPremultiplied); 1305 } 1306 1307 /** 1308 * Indicates whether the renderer responsible for drawing this 1309 * bitmap should attempt to use mipmaps when this bitmap is drawn 1310 * scaled down. 1311 * 1312 * If you know that you are going to draw this bitmap at less than 1313 * 50% of its original size, you may be able to obtain a higher 1314 * quality 1315 * 1316 * This property is only a suggestion that can be ignored by the 1317 * renderer. It is not guaranteed to have any effect. 1318 * 1319 * @return true if the renderer should attempt to use mipmaps, 1320 * false otherwise 1321 * 1322 * @see #setHasMipMap(boolean) 1323 */ 1324 public final boolean hasMipMap() { 1325 if (mRecycled) { 1326 Log.w(TAG, "Called hasMipMap() on a recycle()'d bitmap! This is undefined behavior!"); 1327 } 1328 return nativeHasMipMap(mNativePtr); 1329 } 1330 1331 /** 1332 * Set a hint for the renderer responsible for drawing this bitmap 1333 * indicating that it should attempt to use mipmaps when this bitmap 1334 * is drawn scaled down. 1335 * 1336 * If you know that you are going to draw this bitmap at less than 1337 * 50% of its original size, you may be able to obtain a higher 1338 * quality by turning this property on. 1339 * 1340 * Note that if the renderer respects this hint it might have to 1341 * allocate extra memory to hold the mipmap levels for this bitmap. 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 * @param hasMipMap indicates whether the renderer should attempt 1347 * to use mipmaps 1348 * 1349 * @see #hasMipMap() 1350 */ 1351 public final void setHasMipMap(boolean hasMipMap) { 1352 checkRecycled("setHasMipMap called on a recycled bitmap"); 1353 nativeSetHasMipMap(mNativePtr, hasMipMap); 1354 } 1355 1356 /** 1357 * Fills the bitmap's pixels with the specified {@link Color}. 1358 * 1359 * @throws IllegalStateException if the bitmap is not mutable. 1360 */ 1361 public void eraseColor(@ColorInt int c) { 1362 checkRecycled("Can't erase a recycled bitmap"); 1363 if (!isMutable()) { 1364 throw new IllegalStateException("cannot erase immutable bitmaps"); 1365 } 1366 nativeErase(mNativePtr, c); 1367 } 1368 1369 /** 1370 * Returns the {@link Color} at the specified location. Throws an exception 1371 * if x or y are out of bounds (negative or >= to the width or height 1372 * respectively). The returned color is a non-premultiplied ARGB value. 1373 * 1374 * @param x The x coordinate (0...width-1) of the pixel to return 1375 * @param y The y coordinate (0...height-1) of the pixel to return 1376 * @return The argb {@link Color} at the specified coordinate 1377 * @throws IllegalArgumentException if x, y exceed the bitmap's bounds 1378 */ 1379 @ColorInt 1380 public int getPixel(int x, int y) { 1381 checkRecycled("Can't call getPixel() on a recycled bitmap"); 1382 checkPixelAccess(x, y); 1383 return nativeGetPixel(mNativePtr, x, y); 1384 } 1385 1386 /** 1387 * Returns in pixels[] a copy of the data in the bitmap. Each value is 1388 * a packed int representing a {@link Color}. The stride parameter allows 1389 * the caller to allow for gaps in the returned pixels array between 1390 * rows. For normal packed results, just pass width for the stride value. 1391 * The returned colors are non-premultiplied ARGB values. 1392 * 1393 * @param pixels The array to receive the bitmap's colors 1394 * @param offset The first index to write into pixels[] 1395 * @param stride The number of entries in pixels[] to skip between 1396 * rows (must be >= bitmap's width). Can be negative. 1397 * @param x The x coordinate of the first pixel to read from 1398 * the bitmap 1399 * @param y The y coordinate of the first pixel to read from 1400 * the bitmap 1401 * @param width The number of pixels to read from each row 1402 * @param height The number of rows to read 1403 * 1404 * @throws IllegalArgumentException if x, y, width, height exceed the 1405 * bounds of the bitmap, or if abs(stride) < width. 1406 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 1407 * to receive the specified number of pixels. 1408 */ 1409 public void getPixels(@ColorInt int[] pixels, int offset, int stride, 1410 int x, int y, int width, int height) { 1411 checkRecycled("Can't call getPixels() on a recycled bitmap"); 1412 if (width == 0 || height == 0) { 1413 return; // nothing to do 1414 } 1415 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 1416 nativeGetPixels(mNativePtr, pixels, offset, stride, 1417 x, y, width, height); 1418 } 1419 1420 /** 1421 * Shared code to check for illegal arguments passed to getPixel() 1422 * or setPixel() 1423 * 1424 * @param x x coordinate of the pixel 1425 * @param y y coordinate of the pixel 1426 */ 1427 private void checkPixelAccess(int x, int y) { 1428 checkXYSign(x, y); 1429 if (x >= getWidth()) { 1430 throw new IllegalArgumentException("x must be < bitmap.width()"); 1431 } 1432 if (y >= getHeight()) { 1433 throw new IllegalArgumentException("y must be < bitmap.height()"); 1434 } 1435 } 1436 1437 /** 1438 * Shared code to check for illegal arguments passed to getPixels() 1439 * or setPixels() 1440 * 1441 * @param x left edge of the area of pixels to access 1442 * @param y top edge of the area of pixels to access 1443 * @param width width of the area of pixels to access 1444 * @param height height of the area of pixels to access 1445 * @param offset offset into pixels[] array 1446 * @param stride number of elements in pixels[] between each logical row 1447 * @param pixels array to hold the area of pixels being accessed 1448 */ 1449 private void checkPixelsAccess(int x, int y, int width, int height, 1450 int offset, int stride, int pixels[]) { 1451 checkXYSign(x, y); 1452 if (width < 0) { 1453 throw new IllegalArgumentException("width must be >= 0"); 1454 } 1455 if (height < 0) { 1456 throw new IllegalArgumentException("height must be >= 0"); 1457 } 1458 if (x + width > getWidth()) { 1459 throw new IllegalArgumentException( 1460 "x + width must be <= bitmap.width()"); 1461 } 1462 if (y + height > getHeight()) { 1463 throw new IllegalArgumentException( 1464 "y + height must be <= bitmap.height()"); 1465 } 1466 if (Math.abs(stride) < width) { 1467 throw new IllegalArgumentException("abs(stride) must be >= width"); 1468 } 1469 int lastScanline = offset + (height - 1) * stride; 1470 int length = pixels.length; 1471 if (offset < 0 || (offset + width > length) 1472 || lastScanline < 0 1473 || (lastScanline + width > length)) { 1474 throw new ArrayIndexOutOfBoundsException(); 1475 } 1476 } 1477 1478 /** 1479 * <p>Write the specified {@link Color} into the bitmap (assuming it is 1480 * mutable) at the x,y coordinate. The color must be a 1481 * non-premultiplied ARGB value.</p> 1482 * 1483 * @param x The x coordinate of the pixel to replace (0...width-1) 1484 * @param y The y coordinate of the pixel to replace (0...height-1) 1485 * @param color The ARGB color to write into the bitmap 1486 * 1487 * @throws IllegalStateException if the bitmap is not mutable 1488 * @throws IllegalArgumentException if x, y are outside of the bitmap's 1489 * bounds. 1490 */ 1491 public void setPixel(int x, int y, @ColorInt int color) { 1492 checkRecycled("Can't call setPixel() on a recycled bitmap"); 1493 if (!isMutable()) { 1494 throw new IllegalStateException(); 1495 } 1496 checkPixelAccess(x, y); 1497 nativeSetPixel(mNativePtr, x, y, color); 1498 } 1499 1500 /** 1501 * <p>Replace pixels in the bitmap with the colors in the array. Each element 1502 * in the array is a packed int prepresenting a non-premultiplied ARGB 1503 * {@link Color}.</p> 1504 * 1505 * @param pixels The colors to write to the bitmap 1506 * @param offset The index of the first color to read from pixels[] 1507 * @param stride The number of colors in pixels[] to skip between rows. 1508 * Normally this value will be the same as the width of 1509 * the bitmap, but it can be larger (or negative). 1510 * @param x The x coordinate of the first pixel to write to in 1511 * the bitmap. 1512 * @param y The y coordinate of the first pixel to write to in 1513 * the bitmap. 1514 * @param width The number of colors to copy from pixels[] per row 1515 * @param height The number of rows to write to the bitmap 1516 * 1517 * @throws IllegalStateException if the bitmap is not mutable 1518 * @throws IllegalArgumentException if x, y, width, height are outside of 1519 * the bitmap's bounds. 1520 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 1521 * to receive the specified number of pixels. 1522 */ 1523 public void setPixels(@ColorInt int[] pixels, int offset, int stride, 1524 int x, int y, int width, int height) { 1525 checkRecycled("Can't call setPixels() on a recycled bitmap"); 1526 if (!isMutable()) { 1527 throw new IllegalStateException(); 1528 } 1529 if (width == 0 || height == 0) { 1530 return; // nothing to do 1531 } 1532 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 1533 nativeSetPixels(mNativePtr, pixels, offset, stride, 1534 x, y, width, height); 1535 } 1536 1537 public static final Parcelable.Creator<Bitmap> CREATOR 1538 = new Parcelable.Creator<Bitmap>() { 1539 /** 1540 * Rebuilds a bitmap previously stored with writeToParcel(). 1541 * 1542 * @param p Parcel object to read the bitmap from 1543 * @return a new bitmap created from the data in the parcel 1544 */ 1545 public Bitmap createFromParcel(Parcel p) { 1546 Bitmap bm = nativeCreateFromParcel(p); 1547 if (bm == null) { 1548 throw new RuntimeException("Failed to unparcel Bitmap"); 1549 } 1550 return bm; 1551 } 1552 public Bitmap[] newArray(int size) { 1553 return new Bitmap[size]; 1554 } 1555 }; 1556 1557 /** 1558 * No special parcel contents. 1559 */ 1560 public int describeContents() { 1561 return 0; 1562 } 1563 1564 /** 1565 * Write the bitmap and its pixels to the parcel. The bitmap can be 1566 * rebuilt from the parcel by calling CREATOR.createFromParcel(). 1567 * @param p Parcel object to write the bitmap data into 1568 */ 1569 public void writeToParcel(Parcel p, int flags) { 1570 checkRecycled("Can't parcel a recycled bitmap"); 1571 if (!nativeWriteToParcel(mNativePtr, mIsMutable, mDensity, p)) { 1572 throw new RuntimeException("native writeToParcel failed"); 1573 } 1574 } 1575 1576 /** 1577 * Returns a new bitmap that captures the alpha values of the original. 1578 * This may be drawn with Canvas.drawBitmap(), where the color(s) will be 1579 * taken from the paint that is passed to the draw call. 1580 * 1581 * @return new bitmap containing the alpha channel of the original bitmap. 1582 */ 1583 @CheckResult 1584 public Bitmap extractAlpha() { 1585 return extractAlpha(null, null); 1586 } 1587 1588 /** 1589 * Returns a new bitmap that captures the alpha values of the original. 1590 * These values may be affected by the optional Paint parameter, which 1591 * can contain its own alpha, and may also contain a MaskFilter which 1592 * could change the actual dimensions of the resulting bitmap (e.g. 1593 * a blur maskfilter might enlarge the resulting bitmap). If offsetXY 1594 * is not null, it returns the amount to offset the returned bitmap so 1595 * that it will logically align with the original. For example, if the 1596 * paint contains a blur of radius 2, then offsetXY[] would contains 1597 * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then 1598 * drawing the original would result in the blur visually aligning with 1599 * the original. 1600 * 1601 * <p>The initial density of the returned bitmap is the same as the original's. 1602 * 1603 * @param paint Optional paint used to modify the alpha values in the 1604 * resulting bitmap. Pass null for default behavior. 1605 * @param offsetXY Optional array that returns the X (index 0) and Y 1606 * (index 1) offset needed to position the returned bitmap 1607 * so that it visually lines up with the original. 1608 * @return new bitmap containing the (optionally modified by paint) alpha 1609 * channel of the original bitmap. This may be drawn with 1610 * Canvas.drawBitmap(), where the color(s) will be taken from the 1611 * paint that is passed to the draw call. 1612 */ 1613 @CheckResult 1614 public Bitmap extractAlpha(Paint paint, int[] offsetXY) { 1615 checkRecycled("Can't extractAlpha on a recycled bitmap"); 1616 long nativePaint = paint != null ? paint.getNativeInstance() : 0; 1617 Bitmap bm = nativeExtractAlpha(mNativePtr, nativePaint, offsetXY); 1618 if (bm == null) { 1619 throw new RuntimeException("Failed to extractAlpha on Bitmap"); 1620 } 1621 bm.mDensity = mDensity; 1622 return bm; 1623 } 1624 1625 /** 1626 * Given another bitmap, return true if it has the same dimensions, config, 1627 * and pixel data as this bitmap. If any of those differ, return false. 1628 * If other is null, return false. 1629 */ 1630 public boolean sameAs(Bitmap other) { 1631 checkRecycled("Can't call sameAs on a recycled bitmap!"); 1632 if (this == other) return true; 1633 if (other == null) return false; 1634 if (other.isRecycled()) { 1635 throw new IllegalArgumentException("Can't compare to a recycled bitmap!"); 1636 } 1637 return nativeSameAs(mNativePtr, other.mNativePtr); 1638 } 1639 1640 /** 1641 * Rebuilds any caches associated with the bitmap that are used for 1642 * drawing it. In the case of purgeable bitmaps, this call will attempt to 1643 * ensure that the pixels have been decoded. 1644 * If this is called on more than one bitmap in sequence, the priority is 1645 * given in LRU order (i.e. the last bitmap called will be given highest 1646 * priority). 1647 * 1648 * For bitmaps with no associated caches, this call is effectively a no-op, 1649 * and therefore is harmless. 1650 */ 1651 public void prepareToDraw() { 1652 checkRecycled("Can't prepareToDraw on a recycled bitmap!"); 1653 // Kick off an update/upload of the bitmap outside of the normal 1654 // draw path. 1655 nativePrepareToDraw(mNativePtr); 1656 } 1657 1658 //////////// native methods 1659 1660 private static native Bitmap nativeCreate(int[] colors, int offset, 1661 int stride, int width, int height, 1662 int nativeConfig, boolean mutable); 1663 private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig, 1664 boolean isMutable); 1665 private static native Bitmap nativeCopyAshmem(long nativeSrcBitmap); 1666 private static native Bitmap nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig); 1667 private static native long nativeGetNativeFinalizer(); 1668 private static native boolean nativeRecycle(long nativeBitmap); 1669 private static native void nativeReconfigure(long nativeBitmap, int width, int height, 1670 int config, boolean isPremultiplied); 1671 1672 private static native boolean nativeCompress(long nativeBitmap, int format, 1673 int quality, OutputStream stream, 1674 byte[] tempStorage); 1675 private static native void nativeErase(long nativeBitmap, int color); 1676 private static native int nativeRowBytes(long nativeBitmap); 1677 private static native int nativeConfig(long nativeBitmap); 1678 1679 private static native int nativeGetPixel(long nativeBitmap, int x, int y); 1680 private static native void nativeGetPixels(long nativeBitmap, int[] pixels, 1681 int offset, int stride, int x, int y, 1682 int width, int height); 1683 1684 private static native void nativeSetPixel(long nativeBitmap, int x, int y, int color); 1685 private static native void nativeSetPixels(long nativeBitmap, int[] colors, 1686 int offset, int stride, int x, int y, 1687 int width, int height); 1688 private static native void nativeCopyPixelsToBuffer(long nativeBitmap, 1689 Buffer dst); 1690 private static native void nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src); 1691 private static native int nativeGenerationId(long nativeBitmap); 1692 1693 private static native Bitmap nativeCreateFromParcel(Parcel p); 1694 // returns true on success 1695 private static native boolean nativeWriteToParcel(long nativeBitmap, 1696 boolean isMutable, 1697 int density, 1698 Parcel p); 1699 // returns a new bitmap built from the native bitmap's alpha, and the paint 1700 private static native Bitmap nativeExtractAlpha(long nativeBitmap, 1701 long nativePaint, 1702 int[] offsetXY); 1703 1704 private static native boolean nativeHasAlpha(long nativeBitmap); 1705 private static native boolean nativeIsPremultiplied(long nativeBitmap); 1706 private static native void nativeSetPremultiplied(long nativeBitmap, 1707 boolean isPremul); 1708 private static native void nativeSetHasAlpha(long nativeBitmap, 1709 boolean hasAlpha, 1710 boolean requestPremul); 1711 private static native boolean nativeHasMipMap(long nativeBitmap); 1712 private static native void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap); 1713 private static native boolean nativeSameAs(long nativeBitmap0, long nativeBitmap1); 1714 private static native void nativePrepareToDraw(long nativeBitmap); 1715 private static native int nativeGetAllocationByteCount(long nativeBitmap); 1716} 1717