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