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