Bitmap.java revision b2915245b74b3b5541b123e38403f8e26426b4b7
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.graphics;
18
19import android.annotation.NonNull;
20import android.os.Parcel;
21import android.os.Parcelable;
22import android.os.Trace;
23import android.util.DisplayMetrics;
24
25import dalvik.system.VMRuntime;
26
27import java.io.OutputStream;
28import java.nio.Buffer;
29import java.nio.ByteBuffer;
30import java.nio.IntBuffer;
31import java.nio.ShortBuffer;
32
33public final class Bitmap implements Parcelable {
34    /**
35     * Indicates that the bitmap was created for an unknown pixel density.
36     *
37     * @see Bitmap#getDensity()
38     * @see Bitmap#setDensity(int)
39     */
40    public static final int DENSITY_NONE = 0;
41
42    private final long mSkBitmapPtr;
43
44    /**
45     * Backing buffer for the Bitmap.
46     */
47    private byte[] mBuffer;
48
49    private final BitmapFinalizer mFinalizer;
50
51    private final boolean mIsMutable;
52
53    /**
54     * Represents whether the Bitmap's content is requested to be pre-multiplied.
55     * Note that isPremultiplied() does not directly return this value, because
56     * isPremultiplied() may never return true for a 565 Bitmap or a bitmap
57     * without alpha.
58     *
59     * setPremultiplied() does directly set the value so that setConfig() and
60     * setPremultiplied() aren't order dependent, despite being setters.
61     *
62     * The native bitmap's premultiplication state is kept up to date by
63     * pushing down this preference for every config change.
64     */
65    private boolean mRequestPremultiplied;
66
67    private byte[] mNinePatchChunk; // may be null
68    private NinePatch.InsetStruct mNinePatchInsets; // may be null
69    private int mWidth;
70    private int mHeight;
71    private boolean mRecycled;
72
73    // Package-scoped for fast access.
74    int mDensity = getDefaultDensity();
75
76    private static volatile Matrix sScaleMatrix;
77
78    private static volatile int sDefaultDensity = -1;
79
80    /**
81     * For backwards compatibility, allows the app layer to change the default
82     * density when running old apps.
83     * @hide
84     */
85    public static void setDefaultDensity(int density) {
86        sDefaultDensity = density;
87    }
88
89    @SuppressWarnings("deprecation")
90    static int getDefaultDensity() {
91        if (sDefaultDensity >= 0) {
92            return sDefaultDensity;
93        }
94        sDefaultDensity = DisplayMetrics.DENSITY_DEVICE;
95        return sDefaultDensity;
96    }
97
98    /**
99     * Private constructor that must received an already allocated native bitmap
100     * int (pointer).
101     */
102    // called from JNI
103    Bitmap(long nativeBitmap, byte[] buffer, int width, int height, int density,
104            boolean isMutable, boolean requestPremultiplied,
105            byte[] ninePatchChunk, NinePatch.InsetStruct ninePatchInsets) {
106        if (nativeBitmap == 0) {
107            throw new RuntimeException("internal error: native bitmap is 0");
108        }
109
110        mWidth = width;
111        mHeight = height;
112        mIsMutable = isMutable;
113        mRequestPremultiplied = requestPremultiplied;
114        mBuffer = buffer;
115
116        // we delete this in our finalizer
117        mSkBitmapPtr = nativeBitmap;
118
119        mNinePatchChunk = ninePatchChunk;
120        mNinePatchInsets = ninePatchInsets;
121        if (density >= 0) {
122            mDensity = density;
123        }
124
125        int nativeAllocationByteCount = buffer == null ? getByteCount() : 0;
126        mFinalizer = new BitmapFinalizer(nativeBitmap, nativeAllocationByteCount);
127    }
128
129    /**
130     * Native bitmap has been reconfigured, so set premult and cached
131     * width/height values
132     */
133    // called from JNI
134    void reinit(int width, int height, boolean requestPremultiplied) {
135        mWidth = width;
136        mHeight = height;
137        mRequestPremultiplied = requestPremultiplied;
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>Note: This may change this result of hasAlpha(). When converting to 565,
197     * the new bitmap will always be considered opaque. When converting from 565,
198     * the new bitmap will be considered non-opaque, and will respect the value
199     * set by setPremultiplied().</p>
200     *
201     * <p>WARNING: This method should NOT be called on a bitmap currently used
202     * by the view system. It does not make guarantees about how the underlying
203     * pixel buffer is remapped to the new config, just that the allocation is
204     * reused. Additionally, the view system does not account for bitmap
205     * properties being modifying during use, e.g. while attached to
206     * drawables.</p>
207     *
208     * @see #setWidth(int)
209     * @see #setHeight(int)
210     * @see #setConfig(Config)
211     */
212    public void reconfigure(int width, int height, Config config) {
213        checkRecycled("Can't call reconfigure() on a recycled bitmap");
214        if (width <= 0 || height <= 0) {
215            throw new IllegalArgumentException("width and height must be > 0");
216        }
217        if (!isMutable()) {
218            throw new IllegalStateException("only mutable bitmaps may be reconfigured");
219        }
220        if (mBuffer == null) {
221            throw new IllegalStateException("native-backed bitmaps may not be reconfigured");
222        }
223
224        nativeReconfigure(mSkBitmapPtr, width, height, config.nativeInt, mBuffer.length,
225                mRequestPremultiplied);
226        mWidth = width;
227        mHeight = height;
228    }
229
230    /**
231     * <p>Convenience method for calling {@link #reconfigure(int, int, Config)}
232     * with the current height and config.</p>
233     *
234     * <p>WARNING: this method should not be used on bitmaps currently used by
235     * the view system, see {@link #reconfigure(int, int, Config)} for more
236     * details.</p>
237     *
238     * @see #reconfigure(int, int, Config)
239     * @see #setHeight(int)
240     * @see #setConfig(Config)
241     */
242    public void setWidth(int width) {
243        reconfigure(width, getHeight(), getConfig());
244    }
245
246    /**
247     * <p>Convenience method for calling {@link #reconfigure(int, int, Config)}
248     * with the current width and config.</p>
249     *
250     * <p>WARNING: this method should not be used on bitmaps currently used by
251     * the view system, see {@link #reconfigure(int, int, Config)} for more
252     * details.</p>
253     *
254     * @see #reconfigure(int, int, Config)
255     * @see #setWidth(int)
256     * @see #setConfig(Config)
257     */
258    public void setHeight(int height) {
259        reconfigure(getWidth(), height, getConfig());
260    }
261
262    /**
263     * <p>Convenience method for calling {@link #reconfigure(int, int, Config)}
264     * with the current height and width.</p>
265     *
266     * <p>WARNING: this method should not be used on bitmaps currently used by
267     * the view system, see {@link #reconfigure(int, int, Config)} for more
268     * details.</p>
269     *
270     * @see #reconfigure(int, int, Config)
271     * @see #setWidth(int)
272     * @see #setHeight(int)
273     */
274    public void setConfig(Config config) {
275        reconfigure(getWidth(), getHeight(), config);
276    }
277
278    /**
279     * Sets the nine patch chunk.
280     *
281     * @param chunk The definition of the nine patch
282     *
283     * @hide
284     */
285    public void setNinePatchChunk(byte[] chunk) {
286        mNinePatchChunk = chunk;
287    }
288
289    /**
290     * Free the native object associated with this bitmap, and clear the
291     * reference to the pixel data. This will not free the pixel data synchronously;
292     * it simply allows it to be garbage collected if there are no other references.
293     * The bitmap is marked as "dead", meaning it will throw an exception if
294     * getPixels() or setPixels() is called, and will draw nothing. This operation
295     * cannot be reversed, so it should only be called if you are sure there are no
296     * further uses for the bitmap. This is an advanced call, and normally need
297     * not be called, since the normal GC process will free up this memory when
298     * there are no more references to this bitmap.
299     */
300    public void recycle() {
301        if (!mRecycled && mFinalizer.mNativeBitmap != 0) {
302            if (nativeRecycle(mSkBitmapPtr)) {
303                // return value indicates whether native pixel object was actually recycled.
304                // false indicates that it is still in use at the native level and these
305                // objects should not be collected now. They will be collected later when the
306                // Bitmap itself is collected.
307                mBuffer = null;
308                mNinePatchChunk = null;
309            }
310            mRecycled = true;
311        }
312    }
313
314    /**
315     * Returns true if this bitmap has been recycled. If so, then it is an error
316     * to try to access its pixels, and the bitmap will not draw.
317     *
318     * @return true if the bitmap has been recycled
319     */
320    public final boolean isRecycled() {
321        return mRecycled;
322    }
323
324    /**
325     * Returns the generation ID of this bitmap. The generation ID changes
326     * whenever the bitmap is modified. This can be used as an efficient way to
327     * check if a bitmap has changed.
328     *
329     * @return The current generation ID for this bitmap.
330     */
331    public int getGenerationId() {
332        return nativeGenerationId(mSkBitmapPtr);
333    }
334
335    /**
336     * This is called by methods that want to throw an exception if the bitmap
337     * has already been recycled.
338     */
339    private void checkRecycled(String errorMessage) {
340        if (mRecycled) {
341            throw new IllegalStateException(errorMessage);
342        }
343    }
344
345    /**
346     * Common code for checking that x and y are >= 0
347     *
348     * @param x x coordinate to ensure is >= 0
349     * @param y y coordinate to ensure is >= 0
350     */
351    private static void checkXYSign(int x, int y) {
352        if (x < 0) {
353            throw new IllegalArgumentException("x must be >= 0");
354        }
355        if (y < 0) {
356            throw new IllegalArgumentException("y must be >= 0");
357        }
358    }
359
360    /**
361     * Common code for checking that width and height are > 0
362     *
363     * @param width  width to ensure is > 0
364     * @param height height to ensure is > 0
365     */
366    private static void checkWidthHeight(int width, int height) {
367        if (width <= 0) {
368            throw new IllegalArgumentException("width must be > 0");
369        }
370        if (height <= 0) {
371            throw new IllegalArgumentException("height must be > 0");
372        }
373    }
374
375    /**
376     * Possible bitmap configurations. A bitmap configuration describes
377     * how pixels are stored. This affects the quality (color depth) as
378     * well as the ability to display transparent/translucent colors.
379     */
380    public enum Config {
381        // these native values must match up with the enum in SkBitmap.h
382
383        /**
384         * Each pixel is stored as a single translucency (alpha) channel.
385         * This is very useful to efficiently store masks for instance.
386         * No color information is stored.
387         * With this configuration, each pixel requires 1 byte of memory.
388         */
389        ALPHA_8     (1),
390
391        /**
392         * Each pixel is stored on 2 bytes and only the RGB channels are
393         * encoded: red is stored with 5 bits of precision (32 possible
394         * values), green is stored with 6 bits of precision (64 possible
395         * values) and blue is stored with 5 bits of precision.
396         *
397         * This configuration can produce slight visual artifacts depending
398         * on the configuration of the source. For instance, without
399         * dithering, the result might show a greenish tint. To get better
400         * results dithering should be applied.
401         *
402         * This configuration may be useful when using opaque bitmaps
403         * that do not require high color fidelity.
404         */
405        RGB_565     (3),
406
407        /**
408         * Each pixel is stored on 2 bytes. The three RGB color channels
409         * and the alpha channel (translucency) are stored with a 4 bits
410         * precision (16 possible values.)
411         *
412         * This configuration is mostly useful if the application needs
413         * to store translucency information but also needs to save
414         * memory.
415         *
416         * It is recommended to use {@link #ARGB_8888} instead of this
417         * configuration.
418         *
419         * Note: as of {@link android.os.Build.VERSION_CODES#KITKAT},
420         * any bitmap created with this configuration will be created
421         * using {@link #ARGB_8888} instead.
422         *
423         * @deprecated Because of the poor quality of this configuration,
424         *             it is advised to use {@link #ARGB_8888} instead.
425         */
426        @Deprecated
427        ARGB_4444   (4),
428
429        /**
430         * Each pixel is stored on 4 bytes. Each channel (RGB and alpha
431         * for translucency) is stored with 8 bits of precision (256
432         * possible values.)
433         *
434         * This configuration is very flexible and offers the best
435         * quality. It should be used whenever possible.
436         */
437        ARGB_8888   (5);
438
439        final int nativeInt;
440
441        private static Config sConfigs[] = {
442            null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888
443        };
444
445        Config(int ni) {
446            this.nativeInt = ni;
447        }
448
449        static Config nativeToConfig(int ni) {
450            return sConfigs[ni];
451        }
452    }
453
454    /**
455     * <p>Copy the bitmap's pixels into the specified buffer (allocated by the
456     * caller). An exception is thrown if the buffer is not large enough to
457     * hold all of the pixels (taking into account the number of bytes per
458     * pixel) or if the Buffer subclass is not one of the support types
459     * (ByteBuffer, ShortBuffer, IntBuffer).</p>
460     * <p>The content of the bitmap is copied into the buffer as-is. This means
461     * that if this bitmap stores its pixels pre-multiplied
462     * (see {@link #isPremultiplied()}, the values in the buffer will also be
463     * pre-multiplied.</p>
464     * <p>After this method returns, the current position of the buffer is
465     * updated: the position is incremented by the number of elements written
466     * in the buffer.</p>
467     */
468    public void copyPixelsToBuffer(Buffer dst) {
469        int elements = dst.remaining();
470        int shift;
471        if (dst instanceof ByteBuffer) {
472            shift = 0;
473        } else if (dst instanceof ShortBuffer) {
474            shift = 1;
475        } else if (dst instanceof IntBuffer) {
476            shift = 2;
477        } else {
478            throw new RuntimeException("unsupported Buffer subclass");
479        }
480
481        long bufferSize = (long)elements << shift;
482        long pixelSize = getByteCount();
483
484        if (bufferSize < pixelSize) {
485            throw new RuntimeException("Buffer not large enough for pixels");
486        }
487
488        nativeCopyPixelsToBuffer(mSkBitmapPtr, dst);
489
490        // now update the buffer's position
491        int position = dst.position();
492        position += pixelSize >> shift;
493        dst.position(position);
494    }
495
496    /**
497     * <p>Copy the pixels from the buffer, beginning at the current position,
498     * overwriting the bitmap's pixels. The data in the buffer is not changed
499     * in any way (unlike setPixels(), which converts from unpremultipled 32bit
500     * to whatever the bitmap's native format is.</p>
501     * <p>After this method returns, the current position of the buffer is
502     * updated: the position is incremented by the number of elements read from
503     * the buffer. If you need to read the bitmap from the buffer again you must
504     * first rewind the buffer.</p>
505     */
506    public void copyPixelsFromBuffer(Buffer src) {
507        checkRecycled("copyPixelsFromBuffer called on recycled bitmap");
508
509        int elements = src.remaining();
510        int shift;
511        if (src instanceof ByteBuffer) {
512            shift = 0;
513        } else if (src instanceof ShortBuffer) {
514            shift = 1;
515        } else if (src instanceof IntBuffer) {
516            shift = 2;
517        } else {
518            throw new RuntimeException("unsupported Buffer subclass");
519        }
520
521        long bufferBytes = (long) elements << shift;
522        long bitmapBytes = getByteCount();
523
524        if (bufferBytes < bitmapBytes) {
525            throw new RuntimeException("Buffer not large enough for pixels");
526        }
527
528        nativeCopyPixelsFromBuffer(mSkBitmapPtr, src);
529
530        // now update the buffer's position
531        int position = src.position();
532        position += bitmapBytes >> shift;
533        src.position(position);
534    }
535
536    /**
537     * Tries to make a new bitmap based on the dimensions of this bitmap,
538     * setting the new bitmap's config to the one specified, and then copying
539     * this bitmap's pixels into the new bitmap. If the conversion is not
540     * supported, or the allocator fails, then this returns NULL.  The returned
541     * bitmap initially has the same density as the original.
542     *
543     * @param config    The desired config for the resulting bitmap
544     * @param isMutable True if the resulting bitmap should be mutable (i.e.
545     *                  its pixels can be modified)
546     * @return the new bitmap, or null if the copy could not be made.
547     */
548    public Bitmap copy(Config config, boolean isMutable) {
549        checkRecycled("Can't copy a recycled bitmap");
550        Bitmap b = nativeCopy(mSkBitmapPtr, config.nativeInt, isMutable);
551        if (b != null) {
552            b.setPremultiplied(mRequestPremultiplied);
553            b.mDensity = mDensity;
554        }
555        return b;
556    }
557
558    /**
559     * Creates a new bitmap, scaled from an existing bitmap, when possible. If the
560     * specified width and height are the same as the current width and height of
561     * the source bitmap, the source bitmap is returned and no new bitmap is
562     * created.
563     *
564     * @param src       The source bitmap.
565     * @param dstWidth  The new bitmap's desired width.
566     * @param dstHeight The new bitmap's desired height.
567     * @param filter    true if the source should be filtered.
568     * @return The new scaled bitmap or the source bitmap if no scaling is required.
569     * @throws IllegalArgumentException if width is <= 0, or height is <= 0
570     */
571    public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight,
572            boolean filter) {
573        Matrix m;
574        synchronized (Bitmap.class) {
575            // small pool of just 1 matrix
576            m = sScaleMatrix;
577            sScaleMatrix = null;
578        }
579
580        if (m == null) {
581            m = new Matrix();
582        }
583
584        final int width = src.getWidth();
585        final int height = src.getHeight();
586        final float sx = dstWidth  / (float)width;
587        final float sy = dstHeight / (float)height;
588        m.setScale(sx, sy);
589        Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
590
591        synchronized (Bitmap.class) {
592            // do we need to check for null? why not just assign everytime?
593            if (sScaleMatrix == null) {
594                sScaleMatrix = m;
595            }
596        }
597
598        return b;
599    }
600
601    /**
602     * Returns an immutable bitmap from the source bitmap. The new bitmap may
603     * be the same object as source, or a copy may have been made.  It is
604     * initialized with the same density as the original bitmap.
605     */
606    public static Bitmap createBitmap(Bitmap src) {
607        return createBitmap(src, 0, 0, src.getWidth(), src.getHeight());
608    }
609
610    /**
611     * Returns an immutable bitmap from the specified subset of the source
612     * bitmap. The new bitmap may be the same object as source, or a copy may
613     * have been made. It is initialized with the same density as the original
614     * bitmap.
615     *
616     * @param source   The bitmap we are subsetting
617     * @param x        The x coordinate of the first pixel in source
618     * @param y        The y coordinate of the first pixel in source
619     * @param width    The number of pixels in each row
620     * @param height   The number of rows
621     * @return A copy of a subset of the source bitmap or the source bitmap itself.
622     * @throws IllegalArgumentException if the x, y, width, height values are
623     *         outside of the dimensions of the source bitmap, or width is <= 0,
624     *         or height is <= 0
625     */
626    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) {
627        return createBitmap(source, x, y, width, height, null, false);
628    }
629
630    /**
631     * Returns an immutable bitmap from subset of the source bitmap,
632     * transformed by the optional matrix. The new bitmap may be the
633     * same object as source, or a copy may have been made. It is
634     * initialized with the same density as the original bitmap.
635     *
636     * If the source bitmap is immutable and the requested subset is the
637     * same as the source bitmap itself, then the source bitmap is
638     * returned and no new bitmap is created.
639     *
640     * @param source   The bitmap we are subsetting
641     * @param x        The x coordinate of the first pixel in source
642     * @param y        The y coordinate of the first pixel in source
643     * @param width    The number of pixels in each row
644     * @param height   The number of rows
645     * @param m        Optional matrix to be applied to the pixels
646     * @param filter   true if the source should be filtered.
647     *                   Only applies if the matrix contains more than just
648     *                   translation.
649     * @return A bitmap that represents the specified subset of source
650     * @throws IllegalArgumentException if the x, y, width, height values are
651     *         outside of the dimensions of the source bitmap, or width is <= 0,
652     *         or height is <= 0
653     */
654    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
655            Matrix m, boolean filter) {
656
657        checkXYSign(x, y);
658        checkWidthHeight(width, height);
659        if (x + width > source.getWidth()) {
660            throw new IllegalArgumentException("x + width must be <= bitmap.width()");
661        }
662        if (y + height > source.getHeight()) {
663            throw new IllegalArgumentException("y + height must be <= bitmap.height()");
664        }
665
666        // check if we can just return our argument unchanged
667        if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
668                height == source.getHeight() && (m == null || m.isIdentity())) {
669            return source;
670        }
671
672        int neww = width;
673        int newh = height;
674        Canvas canvas = new Canvas();
675        Bitmap bitmap;
676        Paint paint;
677
678        Rect srcR = new Rect(x, y, x + width, y + height);
679        RectF dstR = new RectF(0, 0, width, height);
680
681        Config newConfig = Config.ARGB_8888;
682        final Config config = source.getConfig();
683        // GIF files generate null configs, assume ARGB_8888
684        if (config != null) {
685            switch (config) {
686                case RGB_565:
687                    newConfig = Config.RGB_565;
688                    break;
689                case ALPHA_8:
690                    newConfig = Config.ALPHA_8;
691                    break;
692                //noinspection deprecation
693                case ARGB_4444:
694                case ARGB_8888:
695                default:
696                    newConfig = Config.ARGB_8888;
697                    break;
698            }
699        }
700
701        if (m == null || m.isIdentity()) {
702            bitmap = createBitmap(neww, newh, newConfig, source.hasAlpha());
703            paint = null;   // not needed
704        } else {
705            final boolean transformed = !m.rectStaysRect();
706
707            RectF deviceR = new RectF();
708            m.mapRect(deviceR, dstR);
709
710            neww = Math.round(deviceR.width());
711            newh = Math.round(deviceR.height());
712
713            bitmap = createBitmap(neww, newh, transformed ? Config.ARGB_8888 : newConfig,
714                    transformed || source.hasAlpha());
715
716            canvas.translate(-deviceR.left, -deviceR.top);
717            canvas.concat(m);
718
719            paint = new Paint();
720            paint.setFilterBitmap(filter);
721            if (transformed) {
722                paint.setAntiAlias(true);
723            }
724        }
725
726        // The new bitmap was created from a known bitmap source so assume that
727        // they use the same density
728        bitmap.mDensity = source.mDensity;
729        bitmap.setHasAlpha(source.hasAlpha());
730        bitmap.setPremultiplied(source.mRequestPremultiplied);
731
732        canvas.setBitmap(bitmap);
733        canvas.drawBitmap(source, srcR, dstR, paint);
734        canvas.setBitmap(null);
735
736        return bitmap;
737    }
738
739    /**
740     * Returns a mutable bitmap with the specified width and height.  Its
741     * initial density is as per {@link #getDensity}.
742     *
743     * @param width    The width of the bitmap
744     * @param height   The height of the bitmap
745     * @param config   The bitmap config to create.
746     * @throws IllegalArgumentException if the width or height are <= 0
747     */
748    public static Bitmap createBitmap(int width, int height, Config config) {
749        return createBitmap(width, height, config, true);
750    }
751
752    /**
753     * Returns a mutable bitmap with the specified width and height.  Its
754     * initial density is determined from the given {@link DisplayMetrics}.
755     *
756     * @param display  Display metrics for the display this bitmap will be
757     *                 drawn on.
758     * @param width    The width of the bitmap
759     * @param height   The height of the bitmap
760     * @param config   The bitmap config to create.
761     * @throws IllegalArgumentException if the width or height are <= 0
762     */
763    public static Bitmap createBitmap(DisplayMetrics display, int width,
764            int height, Config config) {
765        return createBitmap(display, width, height, config, true);
766    }
767
768    /**
769     * Returns a mutable bitmap with the specified width and height.  Its
770     * initial density is as per {@link #getDensity}.
771     *
772     * @param width    The width of the bitmap
773     * @param height   The height of the bitmap
774     * @param config   The bitmap config to create.
775     * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the
776     *                 bitmap as opaque. Doing so will clear the bitmap in black
777     *                 instead of transparent.
778     *
779     * @throws IllegalArgumentException if the width or height are <= 0
780     */
781    private static Bitmap createBitmap(int width, int height, Config config, boolean hasAlpha) {
782        return createBitmap(null, width, height, config, hasAlpha);
783    }
784
785    /**
786     * Returns a mutable bitmap with the specified width and height.  Its
787     * initial density is determined from the given {@link DisplayMetrics}.
788     *
789     * @param display  Display metrics for the display this bitmap will be
790     *                 drawn on.
791     * @param width    The width of the bitmap
792     * @param height   The height of the bitmap
793     * @param config   The bitmap config to create.
794     * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the
795     *                 bitmap as opaque. Doing so will clear the bitmap in black
796     *                 instead of transparent.
797     *
798     * @throws IllegalArgumentException if the width or height are <= 0
799     */
800    private static Bitmap createBitmap(DisplayMetrics display, int width, int height,
801            Config config, boolean hasAlpha) {
802        if (width <= 0 || height <= 0) {
803            throw new IllegalArgumentException("width and height must be > 0");
804        }
805        Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true);
806        if (display != null) {
807            bm.mDensity = display.densityDpi;
808        }
809        bm.setHasAlpha(hasAlpha);
810        if (config == Config.ARGB_8888 && !hasAlpha) {
811            nativeErase(bm.mSkBitmapPtr, 0xff000000);
812        }
813        // No need to initialize the bitmap to zeroes with other configs;
814        // it is backed by a VM byte array which is by definition preinitialized
815        // to all zeroes.
816        return bm;
817    }
818
819    /**
820     * Returns a immutable bitmap with the specified width and height, with each
821     * pixel value set to the corresponding value in the colors array.  Its
822     * initial density is as per {@link #getDensity}.
823     *
824     * @param colors   Array of {@link Color} used to initialize the pixels.
825     * @param offset   Number of values to skip before the first color in the
826     *                 array of colors.
827     * @param stride   Number of colors in the array between rows (must be >=
828     *                 width or <= -width).
829     * @param width    The width of the bitmap
830     * @param height   The height of the bitmap
831     * @param config   The bitmap config to create. If the config does not
832     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
833     *                 bytes in the colors[] will be ignored (assumed to be FF)
834     * @throws IllegalArgumentException if the width or height are <= 0, or if
835     *         the color array's length is less than the number of pixels.
836     */
837    public static Bitmap createBitmap(int colors[], int offset, int stride,
838            int width, int height, Config config) {
839        return createBitmap(null, colors, offset, stride, width, height, config);
840    }
841
842    /**
843     * Returns a immutable bitmap with the specified width and height, with each
844     * pixel value set to the corresponding value in the colors array.  Its
845     * initial density is determined from the given {@link DisplayMetrics}.
846     *
847     * @param display  Display metrics for the display this bitmap will be
848     *                 drawn on.
849     * @param colors   Array of {@link Color} used to initialize the pixels.
850     * @param offset   Number of values to skip before the first color in the
851     *                 array of colors.
852     * @param stride   Number of colors in the array between rows (must be >=
853     *                 width or <= -width).
854     * @param width    The width of the bitmap
855     * @param height   The height of the bitmap
856     * @param config   The bitmap config to create. If the config does not
857     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
858     *                 bytes in the colors[] will be ignored (assumed to be FF)
859     * @throws IllegalArgumentException if the width or height are <= 0, or if
860     *         the color array's length is less than the number of pixels.
861     */
862    public static Bitmap createBitmap(DisplayMetrics display, int colors[],
863            int offset, int stride, int width, int height, Config config) {
864
865        checkWidthHeight(width, height);
866        if (Math.abs(stride) < width) {
867            throw new IllegalArgumentException("abs(stride) must be >= width");
868        }
869        int lastScanline = offset + (height - 1) * stride;
870        int length = colors.length;
871        if (offset < 0 || (offset + width > length) || lastScanline < 0 ||
872                (lastScanline + width > length)) {
873            throw new ArrayIndexOutOfBoundsException();
874        }
875        if (width <= 0 || height <= 0) {
876            throw new IllegalArgumentException("width and height must be > 0");
877        }
878        Bitmap bm = nativeCreate(colors, offset, stride, width, height,
879                            config.nativeInt, false);
880        if (display != null) {
881            bm.mDensity = display.densityDpi;
882        }
883        return bm;
884    }
885
886    /**
887     * Returns a immutable bitmap with the specified width and height, with each
888     * pixel value set to the corresponding value in the colors array.  Its
889     * initial density is as per {@link #getDensity}.
890     *
891     * @param colors   Array of {@link Color} used to initialize the pixels.
892     *                 This array must be at least as large as width * height.
893     * @param width    The width of the bitmap
894     * @param height   The height of the bitmap
895     * @param config   The bitmap config to create. If the config does not
896     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
897     *                 bytes in the colors[] will be ignored (assumed to be FF)
898     * @throws IllegalArgumentException if the width or height are <= 0, or if
899     *         the color array's length is less than the number of pixels.
900     */
901    public static Bitmap createBitmap(int colors[], int width, int height, Config config) {
902        return createBitmap(null, colors, 0, width, width, height, config);
903    }
904
905    /**
906     * Returns a immutable bitmap with the specified width and height, with each
907     * pixel value set to the corresponding value in the colors array.  Its
908     * initial density is determined from the given {@link DisplayMetrics}.
909     *
910     * @param display  Display metrics for the display this bitmap will be
911     *                 drawn on.
912     * @param colors   Array of {@link Color} used to initialize the pixels.
913     *                 This array must be at least as large as width * height.
914     * @param width    The width of the bitmap
915     * @param height   The height of the bitmap
916     * @param config   The bitmap config to create. If the config does not
917     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
918     *                 bytes in the colors[] will be ignored (assumed to be FF)
919     * @throws IllegalArgumentException if the width or height are <= 0, or if
920     *         the color array's length is less than the number of pixels.
921     */
922    public static Bitmap createBitmap(DisplayMetrics display, int colors[],
923            int width, int height, Config config) {
924        return createBitmap(display, colors, 0, width, width, height, config);
925    }
926
927    /**
928     * Returns an optional array of private data, used by the UI system for
929     * some bitmaps. Not intended to be called by applications.
930     */
931    public byte[] getNinePatchChunk() {
932        return mNinePatchChunk;
933    }
934
935    /**
936     * Populates a rectangle with the bitmap's optical insets.
937     *
938     * @param outInsets Rect to populate with optical insets
939     * @hide
940     */
941    public void getOpticalInsets(@NonNull Rect outInsets) {
942        if (mNinePatchInsets == null) {
943            outInsets.setEmpty();
944        } else {
945            outInsets.set(mNinePatchInsets.opticalRect);
946        }
947    }
948
949    /** @hide */
950    public NinePatch.InsetStruct getNinePatchInsets() {
951        return mNinePatchInsets;
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        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress");
1001        boolean result = nativeCompress(mSkBitmapPtr, format.nativeInt, quality,
1002                              stream, new byte[WORKING_COMPRESS_STORAGE]);
1003        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1004        return result;
1005    }
1006
1007    /**
1008     * Returns true if the bitmap is marked as mutable (i.e.&nbsp;can be drawn into)
1009     */
1010    public final boolean isMutable() {
1011        return mIsMutable;
1012    }
1013
1014    /**
1015     * <p>Indicates whether pixels stored in this bitmaps are stored pre-multiplied.
1016     * When a pixel is pre-multiplied, the RGB components have been multiplied by
1017     * the alpha component. For instance, if the original color is a 50%
1018     * translucent red <code>(128, 255, 0, 0)</code>, the pre-multiplied form is
1019     * <code>(128, 128, 0, 0)</code>.</p>
1020     *
1021     * <p>This method always returns false if {@link #getConfig()} is
1022     * {@link Bitmap.Config#RGB_565}.</p>
1023     *
1024     * <p>The return value is undefined if {@link #getConfig()} is
1025     * {@link Bitmap.Config#ALPHA_8}.</p>
1026     *
1027     * <p>This method only returns true if {@link #hasAlpha()} returns true.
1028     * A bitmap with no alpha channel can be used both as a pre-multiplied and
1029     * as a non pre-multiplied bitmap.</p>
1030     *
1031     * <p>Only pre-multiplied bitmaps may be drawn by the view system or
1032     * {@link Canvas}. If a non-pre-multiplied bitmap with an alpha channel is
1033     * drawn to a Canvas, a RuntimeException will be thrown.</p>
1034     *
1035     * @return true if the underlying pixels have been pre-multiplied, false
1036     *         otherwise
1037     *
1038     * @see Bitmap#setPremultiplied(boolean)
1039     * @see BitmapFactory.Options#inPremultiplied
1040     */
1041    public final boolean isPremultiplied() {
1042        return nativeIsPremultiplied(mSkBitmapPtr);
1043    }
1044
1045    /**
1046     * Sets whether the bitmap should treat its data as pre-multiplied.
1047     *
1048     * <p>Bitmaps are always treated as pre-multiplied by the view system and
1049     * {@link Canvas} for performance reasons. Storing un-pre-multiplied data in
1050     * a Bitmap (through {@link #setPixel}, {@link #setPixels}, or {@link
1051     * BitmapFactory.Options#inPremultiplied BitmapFactory.Options.inPremultiplied})
1052     * can lead to incorrect blending if drawn by the framework.</p>
1053     *
1054     * <p>This method will not affect the behavior of a bitmap without an alpha
1055     * channel, or if {@link #hasAlpha()} returns false.</p>
1056     *
1057     * <p>Calling {@link #createBitmap} or {@link #createScaledBitmap} with a source
1058     * Bitmap whose colors are not pre-multiplied may result in a RuntimeException,
1059     * since those functions require drawing the source, which is not supported for
1060     * un-pre-multiplied Bitmaps.</p>
1061     *
1062     * @see Bitmap#isPremultiplied()
1063     * @see BitmapFactory.Options#inPremultiplied
1064     */
1065    public final void setPremultiplied(boolean premultiplied) {
1066        mRequestPremultiplied = premultiplied;
1067        nativeSetPremultiplied(mSkBitmapPtr, 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(mSkBitmapPtr);
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(mSkBitmapPtr));
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(mSkBitmapPtr);
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        nativeSetHasAlpha(mSkBitmapPtr, hasAlpha, mRequestPremultiplied);
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(mSkBitmapPtr);
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(mSkBitmapPtr, 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(mSkBitmapPtr, 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(mSkBitmapPtr, x, y);
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(mSkBitmapPtr, pixels, offset, stride,
1336                        x, y, width, height);
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(mSkBitmapPtr, x, y, color);
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(mSkBitmapPtr, pixels, offset, stride,
1453                        x, y, width, height);
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(mSkBitmapPtr, 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.getNativeInstance() : 0;
1534        Bitmap bm = nativeExtractAlpha(mSkBitmapPtr, 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(mSkBitmapPtr, other.mSkBitmapPtr));
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(mSkBitmapPtr);
1564    }
1565
1566    /** @hide */
1567    public final long getSkBitmap() {
1568        return mSkBitmapPtr;
1569    }
1570
1571    private static class BitmapFinalizer {
1572        private long mNativeBitmap;
1573
1574        // Native memory allocated for the duration of the Bitmap,
1575        // if pixel data allocated into native memory, instead of java byte[]
1576        private final int mNativeAllocationByteCount;
1577
1578        BitmapFinalizer(long nativeBitmap, int nativeAllocationByteCount) {
1579            mNativeBitmap = nativeBitmap;
1580            mNativeAllocationByteCount = nativeAllocationByteCount;
1581
1582            if (mNativeAllocationByteCount != 0) {
1583                VMRuntime.getRuntime().registerNativeAllocation(mNativeAllocationByteCount);
1584            }
1585        }
1586
1587        @Override
1588        public void finalize() {
1589            try {
1590                super.finalize();
1591            } catch (Throwable t) {
1592                // Ignore
1593            } finally {
1594                if (mNativeAllocationByteCount != 0) {
1595                    VMRuntime.getRuntime().registerNativeFree(mNativeAllocationByteCount);
1596                }
1597                nativeDestructor(mNativeBitmap);
1598                mNativeBitmap = 0;
1599            }
1600        }
1601    }
1602
1603    //////////// native methods
1604
1605    private static native Bitmap nativeCreate(int[] colors, int offset,
1606                                              int stride, int width, int height,
1607                                              int nativeConfig, boolean mutable);
1608    private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig,
1609                                            boolean isMutable);
1610    private static native void nativeDestructor(long nativeBitmap);
1611    private static native boolean nativeRecycle(long nativeBitmap);
1612    private static native void nativeReconfigure(long nativeBitmap, int width, int height,
1613                                                 int config, int allocSize,
1614                                                 boolean isPremultiplied);
1615
1616    private static native boolean nativeCompress(long nativeBitmap, int format,
1617                                            int quality, OutputStream stream,
1618                                            byte[] tempStorage);
1619    private static native void nativeErase(long nativeBitmap, int color);
1620    private static native int nativeRowBytes(long nativeBitmap);
1621    private static native int nativeConfig(long nativeBitmap);
1622
1623    private static native int nativeGetPixel(long nativeBitmap, int x, int y);
1624    private static native void nativeGetPixels(long nativeBitmap, int[] pixels,
1625                                               int offset, int stride, int x, int y,
1626                                               int width, int height);
1627
1628    private static native void nativeSetPixel(long nativeBitmap, int x, int y, int color);
1629    private static native void nativeSetPixels(long nativeBitmap, int[] colors,
1630                                               int offset, int stride, int x, int y,
1631                                               int width, int height);
1632    private static native void nativeCopyPixelsToBuffer(long nativeBitmap,
1633                                                        Buffer dst);
1634    private static native void nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src);
1635    private static native int nativeGenerationId(long nativeBitmap);
1636
1637    private static native Bitmap nativeCreateFromParcel(Parcel p);
1638    // returns true on success
1639    private static native boolean nativeWriteToParcel(long nativeBitmap,
1640                                                      boolean isMutable,
1641                                                      int density,
1642                                                      Parcel p);
1643    // returns a new bitmap built from the native bitmap's alpha, and the paint
1644    private static native Bitmap nativeExtractAlpha(long nativeBitmap,
1645                                                    long nativePaint,
1646                                                    int[] offsetXY);
1647
1648    private static native void nativePrepareToDraw(long nativeBitmap);
1649    private static native boolean nativeHasAlpha(long nativeBitmap);
1650    private static native boolean nativeIsPremultiplied(long nativeBitmap);
1651    private static native void nativeSetPremultiplied(long nativeBitmap,
1652                                                      boolean isPremul);
1653    private static native void nativeSetHasAlpha(long nativeBitmap,
1654                                                 boolean hasAlpha,
1655                                                 boolean requestPremul);
1656    private static native boolean nativeHasMipMap(long nativeBitmap);
1657    private static native void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap);
1658    private static native boolean nativeSameAs(long nativeBitmap0, long nativeBitmap1);
1659}
1660