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