Bitmap.java revision f1e484acb594a726fb57ad0ae4cfe902c7f35858
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 java.lang.ref.WeakReference; 20import java.util.ArrayList; 21import java.io.OutputStream; 22import java.nio.Buffer; 23import java.nio.ByteBuffer; 24import java.nio.ShortBuffer; 25import java.nio.IntBuffer; 26 27import android.os.Parcel; 28import android.os.Parcelable; 29 30public final class Bitmap implements Parcelable { 31 32 // Note: mNativeBitmap is used by FaceDetector_jni.cpp 33 // Don't change/rename without updating FaceDetector_jni.cpp 34 private final int mNativeBitmap; 35 36 private final boolean mIsMutable; 37 private byte[] mNinePatchChunk; // may be null 38 private int mWidth = -1; 39 private int mHeight = -1; 40 private boolean mRecycled; 41 42 private static volatile Matrix sScaleMatrix; 43 44 /** 45 * @noinspection UnusedDeclaration 46 */ 47 /* Private constructor that must received an already allocated native 48 bitmap int (pointer). 49 50 This can be called from JNI code. 51 */ 52 private Bitmap(int nativeBitmap, boolean isMutable, byte[] ninePatchChunk) { 53 if (nativeBitmap == 0) { 54 throw new RuntimeException("internal error: native bitmap is 0"); 55 } 56 57 // we delete this in our finalizer 58 mNativeBitmap = nativeBitmap; 59 mIsMutable = isMutable; 60 mNinePatchChunk = ninePatchChunk; 61 } 62 63 /** 64 * Free up the memory associated with this bitmap's pixels, and mark the 65 * bitmap as "dead", meaning it will throw an exception if getPixels() or 66 * setPixels() is called, and will draw nothing. This operation cannot be 67 * reversed, so it should only be called if you are sure there are no 68 * further uses for the bitmap. This is an advanced call, and normally need 69 * not be called, since the normal GC process will free up this memory when 70 * there are no more references to this bitmap. 71 */ 72 public void recycle() { 73 if (!mRecycled) { 74 nativeRecycle(mNativeBitmap); 75 mNinePatchChunk = null; 76 mRecycled = true; 77 } 78 } 79 80 /** 81 * Returns true if this bitmap has been recycled. If so, then it is an error 82 * to try to access its pixels, and the bitmap will not draw. 83 * 84 * @return true if the bitmap has been recycled 85 */ 86 public final boolean isRecycled() { 87 return mRecycled; 88 } 89 90 /** 91 * This is called by methods that want to throw an exception if the bitmap 92 * has already been recycled. 93 */ 94 private void checkRecycled(String errorMessage) { 95 if (mRecycled) { 96 throw new IllegalStateException(errorMessage); 97 } 98 } 99 100 /** 101 * Common code for checking that x and y are >= 0 102 * 103 * @param x x coordinate to ensure is >= 0 104 * @param y y coordinate to ensure is >= 0 105 */ 106 private static void checkXYSign(int x, int y) { 107 if (x < 0) { 108 throw new IllegalArgumentException("x must be >= 0"); 109 } 110 if (y < 0) { 111 throw new IllegalArgumentException("y must be >= 0"); 112 } 113 } 114 115 /** 116 * Common code for checking that width and height are > 0 117 * 118 * @param width width to ensure is > 0 119 * @param height height to ensure is > 0 120 */ 121 private static void checkWidthHeight(int width, int height) { 122 if (width <= 0) { 123 throw new IllegalArgumentException("width must be > 0"); 124 } 125 if (height <= 0) { 126 throw new IllegalArgumentException("height must be > 0"); 127 } 128 } 129 130 public enum Config { 131 // these native values must match up with the enum in SkBitmap.h 132 ALPHA_8 (2), 133 RGB_565 (4), 134 ARGB_4444 (5), 135 ARGB_8888 (6); 136 137 Config(int ni) { 138 this.nativeInt = ni; 139 } 140 final int nativeInt; 141 142 /* package */ static Config nativeToConfig(int ni) { 143 return sConfigs[ni]; 144 } 145 146 private static Config sConfigs[] = { 147 null, null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888 148 }; 149 } 150 151 /** 152 * Copy the bitmap's pixels into the specified buffer (allocated by the 153 * caller). An exception is thrown if the buffer is not large enough to 154 * hold all of the pixels (taking into account the number of bytes per 155 * pixel) or if the Buffer subclass is not one of the support types 156 * (ByteBuffer, ShortBuffer, IntBuffer). 157 */ 158 public void copyPixelsToBuffer(Buffer dst) { 159 int elements = dst.remaining(); 160 int shift; 161 if (dst instanceof ByteBuffer) { 162 shift = 0; 163 } else if (dst instanceof ShortBuffer) { 164 shift = 1; 165 } else if (dst instanceof IntBuffer) { 166 shift = 2; 167 } else { 168 throw new RuntimeException("unsupported Buffer subclass"); 169 } 170 171 long bufferSize = (long)elements << shift; 172 long pixelSize = (long)getRowBytes() * getHeight(); 173 174 if (bufferSize < pixelSize) { 175 throw new RuntimeException("Buffer not large enough for pixels"); 176 } 177 178 nativeCopyPixelsToBuffer(mNativeBitmap, dst); 179 180 // now update the buffer's position 181 int position = dst.position(); 182 position += pixelSize >> shift; 183 dst.position(position); 184 } 185 186 /** 187 * Copy the pixels from the buffer, beginning at the current position, 188 * overwriting the bitmap's pixels. The data in the buffer is not changed 189 * in any way (unlike setPixels(), which converts from unpremultipled 32bit 190 * to whatever the bitmap's native format is. 191 */ 192 public void copyPixelsFromBuffer(Buffer src) { 193 checkRecycled("copyPixelsFromBuffer called on recycled bitmap"); 194 195 int elements = src.remaining(); 196 int shift; 197 if (src instanceof ByteBuffer) { 198 shift = 0; 199 } else if (src instanceof ShortBuffer) { 200 shift = 1; 201 } else if (src instanceof IntBuffer) { 202 shift = 2; 203 } else { 204 throw new RuntimeException("unsupported Buffer subclass"); 205 } 206 207 long bufferBytes = (long)elements << shift; 208 long bitmapBytes = (long)getRowBytes() * getHeight(); 209 210 if (bufferBytes < bitmapBytes) { 211 throw new RuntimeException("Buffer not large enough for pixels"); 212 } 213 214 nativeCopyPixelsFromBuffer(mNativeBitmap, src); 215 } 216 217 /** 218 * Tries to make a new bitmap based on the dimensions of this bitmap, 219 * setting the new bitmap's config to the one specified, and then copying 220 * this bitmap's pixels into the new bitmap. If the conversion is not 221 * supported, or the allocator fails, then this returns NULL. 222 * 223 * @param config The desired config for the resulting bitmap 224 * @param isMutable True if the resulting bitmap should be mutable (i.e. 225 * its pixels can be modified) 226 * @return the new bitmap, or null if the copy could not be made. 227 */ 228 public Bitmap copy(Config config, boolean isMutable) { 229 checkRecycled("Can't copy a recycled bitmap"); 230 return nativeCopy(mNativeBitmap, config.nativeInt, isMutable); 231 } 232 233 public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, 234 int dstHeight, boolean filter) { 235 Matrix m = null; 236 synchronized (Bitmap.class) { 237 // small pool of just 1 matrix 238 m = sScaleMatrix; 239 sScaleMatrix = null; 240 } 241 242 if (m == null) { 243 m = new Matrix(); 244 } 245 246 final int width = src.getWidth(); 247 final int height = src.getHeight(); 248 final float sx = dstWidth / (float)width; 249 final float sy = dstHeight / (float)height; 250 m.setScale(sx, sy); 251 Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter); 252 253 synchronized (Bitmap.class) { 254 // do we need to check for null? why not just assign everytime? 255 if (sScaleMatrix == null) { 256 sScaleMatrix = m; 257 } 258 } 259 260 return b; 261 } 262 263 /** 264 * Returns an immutable bitmap from the source bitmap. The new bitmap may 265 * be the same object as source, or a copy may have been made. 266 */ 267 public static Bitmap createBitmap(Bitmap src) { 268 return createBitmap(src, 0, 0, src.getWidth(), src.getHeight()); 269 } 270 271 /** 272 * Returns an immutable bitmap from the specified subset of the source 273 * bitmap. The new bitmap may be the same object as source, or a copy may 274 * have been made. 275 * 276 * @param source The bitmap we are subsetting 277 * @param x The x coordinate of the first pixel in source 278 * @param y The y coordinate of the first pixel in source 279 * @param width The number of pixels in each row 280 * @param height The number of rows 281 */ 282 public static Bitmap createBitmap(Bitmap source, int x, int y, 283 int width, int height) { 284 return createBitmap(source, x, y, width, height, null, false); 285 } 286 287 /** 288 * Returns an immutable bitmap from subset of the source bitmap, 289 * transformed by the optional matrix. 290 * 291 * @param source The bitmap we are subsetting 292 * @param x The x coordinate of the first pixel in source 293 * @param y The y coordinate of the first pixel in source 294 * @param width The number of pixels in each row 295 * @param height The number of rows 296 * @param m Option matrix to be applied to the pixels 297 * @param filter true if the source should be filtered. 298 * Only applies if the matrix contains more than just 299 * translation. 300 * @return A bitmap that represents the specified subset of source 301 * @throws IllegalArgumentException if the x, y, width, height values are 302 * outside of the dimensions of the source bitmap. 303 */ 304 public static Bitmap createBitmap(Bitmap source, int x, int y, int width, 305 int height, Matrix m, boolean filter) { 306 checkXYSign(x, y); 307 checkWidthHeight(width, height); 308 if (x + width > source.getWidth()) { 309 throw new IllegalArgumentException( 310 "x + width must be <= bitmap.width()"); 311 } 312 if (y + height > source.getHeight()) { 313 throw new IllegalArgumentException( 314 "y + height must be <= bitmap.height()"); 315 } 316 317 // check if we can just return our argument unchanged 318 if (!source.isMutable() && x == 0 && y == 0 319 && width == source.getWidth() && height == source.getHeight() 320 && (m == null || m.isIdentity())) { 321 return source; 322 } 323 324 int neww = width; 325 int newh = height; 326 Canvas canvas = new Canvas(); 327 Bitmap bitmap; 328 Paint paint; 329 330 Rect srcR = new Rect(x, y, x + width, y + height); 331 RectF dstR = new RectF(0, 0, width, height); 332 333 if (m == null || m.isIdentity()) { 334 bitmap = createBitmap(neww, newh, source.hasAlpha() ? 335 Config.ARGB_8888 : Config.RGB_565); 336 paint = null; // not needed 337 } else { 338 /* the dst should have alpha if the src does, or if our matrix 339 doesn't preserve rectness 340 */ 341 boolean hasAlpha = source.hasAlpha() || !m.rectStaysRect(); 342 RectF deviceR = new RectF(); 343 m.mapRect(deviceR, dstR); 344 neww = Math.round(deviceR.width()); 345 newh = Math.round(deviceR.height()); 346 bitmap = createBitmap(neww, newh, hasAlpha ? 347 Config.ARGB_8888 : Config.RGB_565); 348 if (hasAlpha) { 349 bitmap.eraseColor(0); 350 } 351 canvas.translate(-deviceR.left, -deviceR.top); 352 canvas.concat(m); 353 paint = new Paint(); 354 paint.setFilterBitmap(filter); 355 if (!m.rectStaysRect()) { 356 paint.setAntiAlias(true); 357 } 358 } 359 canvas.setBitmap(bitmap); 360 canvas.drawBitmap(source, srcR, dstR, paint); 361 362 return bitmap; 363 } 364 365 /** 366 * Returns a mutable bitmap with the specified width and height. 367 * 368 * @param width The width of the bitmap 369 * @param height The height of the bitmap 370 * @param config The bitmap config to create. 371 * @throws IllegalArgumentException if the width or height are <= 0 372 */ 373 public static Bitmap createBitmap(int width, int height, Config config) { 374 Bitmap bm = nativeCreate(null, 0, width, width, height, 375 config.nativeInt, true); 376 bm.eraseColor(0); // start with black/transparent pixels 377 return bm; 378 } 379 380 /** 381 * Returns a immutable bitmap with the specified width and height, with each 382 * pixel value set to the corresponding value in the colors array. 383 * 384 * @param colors Array of {@link Color} used to initialize the pixels. 385 * @param offset Number of values to skip before the first color in the 386 * array of colors. 387 * @param stride Number of colors in the array between rows (must be >= 388 * width or <= -width). 389 * @param width The width of the bitmap 390 * @param height The height of the bitmap 391 * @param config The bitmap config to create. If the config does not 392 * support per-pixel alpha (e.g. RGB_565), then the alpha 393 * bytes in the colors[] will be ignored (assumed to be FF) 394 * @throws IllegalArgumentException if the width or height are <= 0, or if 395 * the color array's length is less than the number of pixels. 396 */ 397 public static Bitmap createBitmap(int colors[], int offset, int stride, 398 int width, int height, Config config) { 399 checkWidthHeight(width, height); 400 if (Math.abs(stride) < width) { 401 throw new IllegalArgumentException("abs(stride) must be >= width"); 402 } 403 int lastScanline = offset + (height - 1) * stride; 404 int length = colors.length; 405 if (offset < 0 || (offset + width > length) 406 || lastScanline < 0 407 || (lastScanline + width > length)) { 408 throw new ArrayIndexOutOfBoundsException(); 409 } 410 return nativeCreate(colors, offset, stride, width, height, 411 config.nativeInt, false); 412 } 413 414 /** 415 * Returns a immutable bitmap with the specified width and height, with each 416 * pixel value set to the corresponding value in the colors array. 417 * 418 * @param colors Array of {@link Color} used to initialize the pixels. 419 * This array must be at least as large as width * height. 420 * @param width The width of the bitmap 421 * @param height The height of the bitmap 422 * @param config The bitmap config to create. If the config does not 423 * support per-pixel alpha (e.g. RGB_565), then the alpha 424 * bytes in the colors[] will be ignored (assumed to be FF) 425 * @throws IllegalArgumentException if the width or height are <= 0, or if 426 * the color array's length is less than the number of pixels. 427 */ 428 public static Bitmap createBitmap(int colors[], int width, int height, 429 Config config) { 430 return createBitmap(colors, 0, width, width, height, config); 431 } 432 433 /** 434 * Returns an optional array of private data, used by the UI system for 435 * some bitmaps. Not intended to be called by applications. 436 */ 437 public byte[] getNinePatchChunk() { 438 return mNinePatchChunk; 439 } 440 441 /** 442 * Specifies the known formats a bitmap can be compressed into 443 */ 444 public enum CompressFormat { 445 JPEG (0), 446 PNG (1); 447 448 CompressFormat(int nativeInt) { 449 this.nativeInt = nativeInt; 450 } 451 final int nativeInt; 452 } 453 454 /** 455 * Number of bytes of temp storage we use for communicating between the 456 * native compressor and the java OutputStream. 457 */ 458 private final static int WORKING_COMPRESS_STORAGE = 4096; 459 460 /** 461 * Write a compressed version of the bitmap to the specified outputstream. 462 * If this returns true, the bitmap can be reconstructed by passing a 463 * corresponding inputstream to BitmapFactory.decodeStream(). Note: not 464 * all Formats support all bitmap configs directly, so it is possible that 465 * the returned bitmap from BitmapFactory could be in a different bitdepth, 466 * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque 467 * pixels). 468 * 469 * @param format The format of the compressed image 470 * @param quality Hint to the compressor, 0-100. 0 meaning compress for 471 * small size, 100 meaning compress for max quality. Some 472 * formats, like PNG which is lossless, will ignore the 473 * quality setting 474 * @param stream The outputstream to write the compressed data. 475 * @return true if successfully compressed to the specified stream. 476 */ 477 public boolean compress(CompressFormat format, int quality, 478 OutputStream stream) { 479 checkRecycled("Can't compress a recycled bitmap"); 480 // do explicit check before calling the native method 481 if (stream == null) { 482 throw new NullPointerException(); 483 } 484 if (quality < 0 || quality > 100) { 485 throw new IllegalArgumentException("quality must be 0..100"); 486 } 487 return nativeCompress(mNativeBitmap, format.nativeInt, quality, 488 stream, new byte[WORKING_COMPRESS_STORAGE]); 489 } 490 491 /** 492 * Returns true if the bitmap is marked as mutable (i.e. can be drawn into) 493 */ 494 public final boolean isMutable() { 495 return mIsMutable; 496 } 497 498 /** Returns the bitmap's width */ 499 public final int getWidth() { 500 return mWidth == -1 ? mWidth = nativeWidth(mNativeBitmap) : mWidth; 501 } 502 503 /** Returns the bitmap's height */ 504 public final int getHeight() { 505 return mHeight == -1 ? mHeight = nativeHeight(mNativeBitmap) : mHeight; 506 } 507 508 /** 509 * Return the number of bytes between rows in the bitmap's pixels. Note that 510 * this refers to the pixels as stored natively by the bitmap. If you call 511 * getPixels() or setPixels(), then the pixels are uniformly treated as 512 * 32bit values, packed according to the Color class. 513 * 514 * @return number of bytes between rows of the native bitmap pixels. 515 */ 516 public final int getRowBytes() { 517 return nativeRowBytes(mNativeBitmap); 518 } 519 520 /** 521 * If the bitmap's internal config is in one of the public formats, return 522 * that config, otherwise return null. 523 */ 524 public final Config getConfig() { 525 return Config.nativeToConfig(nativeConfig(mNativeBitmap)); 526 } 527 528 /** Returns true if the bitmap's pixels support levels of alpha */ 529 public final boolean hasAlpha() { 530 return nativeHasAlpha(mNativeBitmap); 531 } 532 533 /** 534 * Fills the bitmap's pixels with the specified {@link Color}. 535 * 536 * @throws IllegalStateException if the bitmap is not mutable. 537 */ 538 public void eraseColor(int c) { 539 checkRecycled("Can't erase a recycled bitmap"); 540 if (!isMutable()) { 541 throw new IllegalStateException("cannot erase immutable bitmaps"); 542 } 543 nativeErase(mNativeBitmap, c); 544 } 545 546 /** 547 * Returns the {@link Color} at the specified location. Throws an exception 548 * if x or y are out of bounds (negative or >= to the width or height 549 * respectively). 550 * 551 * @param x The x coordinate (0...width-1) of the pixel to return 552 * @param y The y coordinate (0...height-1) of the pixel to return 553 * @return The argb {@link Color} at the specified coordinate 554 * @throws IllegalArgumentException if x, y exceed the bitmap's bounds 555 */ 556 public int getPixel(int x, int y) { 557 checkRecycled("Can't call getPixel() on a recycled bitmap"); 558 checkPixelAccess(x, y); 559 return nativeGetPixel(mNativeBitmap, x, y); 560 } 561 562 /** 563 * Returns in pixels[] a copy of the data in the bitmap. Each value is 564 * a packed int representing a {@link Color}. The stride parameter allows 565 * the caller to allow for gaps in the returned pixels array between 566 * rows. For normal packed results, just pass width for the stride value. 567 * 568 * @param pixels The array to receive the bitmap's colors 569 * @param offset The first index to write into pixels[] 570 * @param stride The number of entries in pixels[] to skip between 571 * rows (must be >= bitmap's width). Can be negative. 572 * @param x The x coordinate of the first pixel to read from 573 * the bitmap 574 * @param y The y coordinate of the first pixel to read from 575 * the bitmap 576 * @param width The number of pixels to read from each row 577 * @param height The number of rows to read 578 * @throws IllegalArgumentException if x, y, width, height exceed the 579 * bounds of the bitmap, or if abs(stride) < width. 580 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 581 * to receive the specified number of pixels. 582 */ 583 public void getPixels(int[] pixels, int offset, int stride, 584 int x, int y, int width, int height) { 585 checkRecycled("Can't call getPixels() on a recycled bitmap"); 586 if (width == 0 || height == 0) { 587 return; // nothing to do 588 } 589 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 590 nativeGetPixels(mNativeBitmap, pixels, offset, stride, 591 x, y, width, height); 592 } 593 594 /** 595 * Shared code to check for illegal arguments passed to getPixel() 596 * or setPixel() 597 * @param x x coordinate of the pixel 598 * @param y y coordinate of the pixel 599 */ 600 private void checkPixelAccess(int x, int y) { 601 checkXYSign(x, y); 602 if (x >= getWidth()) { 603 throw new IllegalArgumentException("x must be < bitmap.width()"); 604 } 605 if (y >= getHeight()) { 606 throw new IllegalArgumentException("y must be < bitmap.height()"); 607 } 608 } 609 610 /** 611 * Shared code to check for illegal arguments passed to getPixels() 612 * or setPixels() 613 * 614 * @param x left edge of the area of pixels to access 615 * @param y top edge of the area of pixels to access 616 * @param width width of the area of pixels to access 617 * @param height height of the area of pixels to access 618 * @param offset offset into pixels[] array 619 * @param stride number of elements in pixels[] between each logical row 620 * @param pixels array to hold the area of pixels being accessed 621 */ 622 private void checkPixelsAccess(int x, int y, int width, int height, 623 int offset, int stride, int pixels[]) { 624 checkXYSign(x, y); 625 if (width < 0) { 626 throw new IllegalArgumentException("width must be >= 0"); 627 } 628 if (height < 0) { 629 throw new IllegalArgumentException("height must be >= 0"); 630 } 631 if (x + width > getWidth()) { 632 throw new IllegalArgumentException( 633 "x + width must be <= bitmap.width()"); 634 } 635 if (y + height > getHeight()) { 636 throw new IllegalArgumentException( 637 "y + height must be <= bitmap.height()"); 638 } 639 if (Math.abs(stride) < width) { 640 throw new IllegalArgumentException("abs(stride) must be >= width"); 641 } 642 int lastScanline = offset + (height - 1) * stride; 643 int length = pixels.length; 644 if (offset < 0 || (offset + width > length) 645 || lastScanline < 0 646 || (lastScanline + width > length)) { 647 throw new ArrayIndexOutOfBoundsException(); 648 } 649 } 650 651 /** 652 * Write the specified {@link Color} into the bitmap (assuming it is 653 * mutable) at the x,y coordinate. 654 * 655 * @param x The x coordinate of the pixel to replace (0...width-1) 656 * @param y The y coordinate of the pixel to replace (0...height-1) 657 * @param color The {@link Color} to write into the bitmap 658 * @throws IllegalStateException if the bitmap is not mutable 659 * @throws IllegalArgumentException if x, y are outside of the bitmap's 660 * bounds. 661 */ 662 public void setPixel(int x, int y, int color) { 663 checkRecycled("Can't call setPixel() on a recycled bitmap"); 664 if (!isMutable()) { 665 throw new IllegalStateException(); 666 } 667 checkPixelAccess(x, y); 668 nativeSetPixel(mNativeBitmap, x, y, color); 669 } 670 671 /** 672 * Replace pixels in the bitmap with the colors in the array. Each element 673 * in the array is a packed int prepresenting a {@link Color} 674 * 675 * @param pixels The colors to write to the bitmap 676 * @param offset The index of the first color to read from pixels[] 677 * @param stride The number of colors in pixels[] to skip between rows. 678 * Normally this value will be the same as the width of 679 * the bitmap, but it can be larger (or negative). 680 * @param x The x coordinate of the first pixel to write to in 681 * the bitmap. 682 * @param y The y coordinate of the first pixel to write to in 683 * the bitmap. 684 * @param width The number of colors to copy from pixels[] per row 685 * @param height The number of rows to write to the bitmap 686 * @throws IllegalStateException if the bitmap is not mutable 687 * @throws IllegalArgumentException if x, y, width, height are outside of 688 * the bitmap's bounds. 689 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 690 * to receive the specified number of pixels. 691 */ 692 public void setPixels(int[] pixels, int offset, int stride, 693 int x, int y, int width, int height) { 694 checkRecycled("Can't call setPixels() on a recycled bitmap"); 695 if (!isMutable()) { 696 throw new IllegalStateException(); 697 } 698 if (width == 0 || height == 0) { 699 return; // nothing to do 700 } 701 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 702 nativeSetPixels(mNativeBitmap, pixels, offset, stride, 703 x, y, width, height); 704 } 705 706 public static final Parcelable.Creator<Bitmap> CREATOR 707 = new Parcelable.Creator<Bitmap>() { 708 /** 709 * Rebuilds a bitmap previously stored with writeToParcel(). 710 * 711 * @param p Parcel object to read the bitmap from 712 * @return a new bitmap created from the data in the parcel 713 */ 714 public Bitmap createFromParcel(Parcel p) { 715 Bitmap bm = nativeCreateFromParcel(p); 716 if (bm == null) { 717 throw new RuntimeException("Failed to unparcel Bitmap"); 718 } 719 return bm; 720 } 721 public Bitmap[] newArray(int size) { 722 return new Bitmap[size]; 723 } 724 }; 725 726 /** 727 * No special parcel contents. 728 */ 729 public int describeContents() { 730 return 0; 731 } 732 733 /** 734 * Write the bitmap and its pixels to the parcel. The bitmap can be 735 * rebuilt from the parcel by calling CREATOR.createFromParcel(). 736 * @param p Parcel object to write the bitmap data into 737 */ 738 public void writeToParcel(Parcel p, int flags) { 739 checkRecycled("Can't parcel a recycled bitmap"); 740 if (!nativeWriteToParcel(mNativeBitmap, mIsMutable, p)) { 741 throw new RuntimeException("native writeToParcel failed"); 742 } 743 } 744 745 /** 746 * Returns a new bitmap that captures the alpha values of the original. 747 * This may be drawn with Canvas.drawBitmap(), where the color(s) will be 748 * taken from the paint that is passed to the draw call. 749 * 750 * @return new bitmap containing the alpha channel of the original bitmap. 751 */ 752 public Bitmap extractAlpha() { 753 return extractAlpha(null, null); 754 } 755 756 /** 757 * Returns a new bitmap that captures the alpha values of the original. 758 * These values may be affected by the optional Paint parameter, which 759 * can contain its own alpha, and may also contain a MaskFilter which 760 * could change the actual dimensions of the resulting bitmap (e.g. 761 * a blur maskfilter might enlarge the resulting bitmap). If offsetXY 762 * is not null, it returns the amount to offset the returned bitmap so 763 * that it will logically align with the original. For example, if the 764 * paint contains a blur of radius 2, then offsetXY[] would contains 765 * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then 766 * drawing the original would result in the blur visually aligning with 767 * the original. 768 * @param paint Optional paint used to modify the alpha values in the 769 * resulting bitmap. Pass null for default behavior. 770 * @param offsetXY Optional array that returns the X (index 0) and Y 771 * (index 1) offset needed to position the returned bitmap 772 * so that it visually lines up with the original. 773 * @return new bitmap containing the (optionally modified by paint) alpha 774 * channel of the original bitmap. This may be drawn with 775 * Canvas.drawBitmap(), where the color(s) will be taken from the 776 * paint that is passed to the draw call. 777 */ 778 public Bitmap extractAlpha(Paint paint, int[] offsetXY) { 779 checkRecycled("Can't extractAlpha on a recycled bitmap"); 780 int nativePaint = paint != null ? paint.mNativePaint : 0; 781 Bitmap bm = nativeExtractAlpha(mNativeBitmap, nativePaint, offsetXY); 782 if (bm == null) { 783 throw new RuntimeException("Failed to extractAlpha on Bitmap"); 784 } 785 return bm; 786 } 787 788 protected void finalize() throws Throwable { 789 try { 790 nativeDestructor(mNativeBitmap); 791 } finally { 792 super.finalize(); 793 } 794 } 795 796 //////////// native methods 797 798 private static native Bitmap nativeCreate(int[] colors, int offset, 799 int stride, int width, int height, 800 int nativeConfig, boolean mutable); 801 private static native Bitmap nativeCopy(int srcBitmap, int nativeConfig, 802 boolean isMutable); 803 private static native void nativeDestructor(int nativeBitmap); 804 private static native void nativeRecycle(int nativeBitmap); 805 806 private static native boolean nativeCompress(int nativeBitmap, int format, 807 int quality, OutputStream stream, 808 byte[] tempStorage); 809 private static native void nativeErase(int nativeBitmap, int color); 810 private static native int nativeWidth(int nativeBitmap); 811 private static native int nativeHeight(int nativeBitmap); 812 private static native int nativeRowBytes(int nativeBitmap); 813 private static native int nativeConfig(int nativeBitmap); 814 private static native boolean nativeHasAlpha(int nativeBitmap); 815 816 private static native int nativeGetPixel(int nativeBitmap, int x, int y); 817 private static native void nativeGetPixels(int nativeBitmap, int[] pixels, 818 int offset, int stride, int x, 819 int y, int width, int height); 820 821 private static native void nativeSetPixel(int nativeBitmap, int x, int y, 822 int color); 823 private static native void nativeSetPixels(int nativeBitmap, int[] colors, 824 int offset, int stride, int x, 825 int y, int width, int height); 826 private static native void nativeCopyPixelsToBuffer(int nativeBitmap, 827 Buffer dst); 828 private static native void nativeCopyPixelsFromBuffer(int nb, Buffer src); 829 830 private static native Bitmap nativeCreateFromParcel(Parcel p); 831 // returns true on success 832 private static native boolean nativeWriteToParcel(int nativeBitmap, 833 boolean isMutable, 834 Parcel p); 835 // returns a new bitmap built from the native bitmap's alpha, and the paint 836 private static native Bitmap nativeExtractAlpha(int nativeBitmap, 837 int nativePaint, 838 int[] offsetXY); 839 840 /* package */ final int ni() { 841 return mNativeBitmap; 842 } 843} 844