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