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