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