Bitmap.java revision 29cd3e922612afff4cd5fa9694013e5e8ae93661
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. The pixels remain in the color space of the bitmap.</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. The pixels in the source
566     * buffer are assumed to be in the bitmap's color space.</p>
567     * <p>After this method returns, the current position of the buffer is
568     * updated: the position is incremented by the number of elements read from
569     * the buffer. If you need to read the bitmap from the buffer again you must
570     * first rewind the buffer.</p>
571     * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
572     */
573    public void copyPixelsFromBuffer(Buffer src) {
574        checkRecycled("copyPixelsFromBuffer called on recycled bitmap");
575        checkHardware("unable to copyPixelsFromBuffer, Config#HARDWARE bitmaps are immutable");
576
577        int elements = src.remaining();
578        int shift;
579        if (src instanceof ByteBuffer) {
580            shift = 0;
581        } else if (src instanceof ShortBuffer) {
582            shift = 1;
583        } else if (src instanceof IntBuffer) {
584            shift = 2;
585        } else {
586            throw new RuntimeException("unsupported Buffer subclass");
587        }
588
589        long bufferBytes = (long) elements << shift;
590        long bitmapBytes = getByteCount();
591
592        if (bufferBytes < bitmapBytes) {
593            throw new RuntimeException("Buffer not large enough for pixels");
594        }
595
596        nativeCopyPixelsFromBuffer(mNativePtr, src);
597
598        // now update the buffer's position
599        int position = src.position();
600        position += bitmapBytes >> shift;
601        src.position(position);
602    }
603
604    /**
605     * Tries to make a new bitmap based on the dimensions of this bitmap,
606     * setting the new bitmap's config to the one specified, and then copying
607     * this bitmap's pixels into the new bitmap. If the conversion is not
608     * supported, or the allocator fails, then this returns NULL.  The returned
609     * bitmap initially has the same density as the original.
610     *
611     * @param config    The desired config for the resulting bitmap
612     * @param isMutable True if the resulting bitmap should be mutable (i.e.
613     *                  its pixels can be modified)
614     * @return the new bitmap, or null if the copy could not be made.
615     * @throws IllegalArgumentException if config is {@link Config#HARDWARE} and isMutable is true
616     */
617    public Bitmap copy(Config config, boolean isMutable) {
618        checkRecycled("Can't copy a recycled bitmap");
619        if (config == Config.HARDWARE && isMutable) {
620            throw new IllegalArgumentException("Hardware bitmaps are always immutable");
621        }
622        Bitmap b = nativeCopy(mNativePtr, config.nativeInt, isMutable);
623        if (b != null) {
624            b.setPremultiplied(mRequestPremultiplied);
625            b.mDensity = mDensity;
626        }
627        return b;
628    }
629
630    /**
631     * Creates a new immutable bitmap backed by ashmem which can efficiently
632     * be passed between processes.
633     *
634     * @hide
635     */
636    public Bitmap createAshmemBitmap() {
637        checkRecycled("Can't copy a recycled bitmap");
638        Bitmap b = nativeCopyAshmem(mNativePtr);
639        if (b != null) {
640            b.setPremultiplied(mRequestPremultiplied);
641            b.mDensity = mDensity;
642        }
643        return b;
644    }
645
646    /**
647     * Creates a new immutable bitmap backed by ashmem which can efficiently
648     * be passed between processes.
649     *
650     * @hide
651     */
652    public Bitmap createAshmemBitmap(Config config) {
653        checkRecycled("Can't copy a recycled bitmap");
654        Bitmap b = nativeCopyAshmemConfig(mNativePtr, config.nativeInt);
655        if (b != null) {
656            b.setPremultiplied(mRequestPremultiplied);
657            b.mDensity = mDensity;
658        }
659        return b;
660    }
661
662    /**
663     * Create hardware bitmap backed GraphicBuffer.
664     *
665     * @return Bitmap or null if this GraphicBuffer has unsupported PixelFormat.
666     *         currently PIXEL_FORMAT_RGBA_8888 is the only supported format
667     * @hide
668     */
669    public static Bitmap createHardwareBitmap(GraphicBuffer graphicBuffer) {
670        return nativeCreateHardwareBitmap(graphicBuffer);
671    }
672
673    /**
674     * Creates a new bitmap, scaled from an existing bitmap, when possible. If the
675     * specified width and height are the same as the current width and height of
676     * the source bitmap, the source bitmap is returned and no new bitmap is
677     * created.
678     *
679     * @param src       The source bitmap.
680     * @param dstWidth  The new bitmap's desired width.
681     * @param dstHeight The new bitmap's desired height.
682     * @param filter    true if the source should be filtered.
683     * @return The new scaled bitmap or the source bitmap if no scaling is required.
684     * @throws IllegalArgumentException if width is <= 0, or height is <= 0
685     */
686    public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight,
687            boolean filter) {
688        Matrix m;
689        synchronized (Bitmap.class) {
690            // small pool of just 1 matrix
691            m = sScaleMatrix;
692            sScaleMatrix = null;
693        }
694
695        if (m == null) {
696            m = new Matrix();
697        }
698
699        final int width = src.getWidth();
700        final int height = src.getHeight();
701        final float sx = dstWidth  / (float)width;
702        final float sy = dstHeight / (float)height;
703        m.setScale(sx, sy);
704        Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
705
706        synchronized (Bitmap.class) {
707            // do we need to check for null? why not just assign everytime?
708            if (sScaleMatrix == null) {
709                sScaleMatrix = m;
710            }
711        }
712
713        return b;
714    }
715
716    /**
717     * Returns an immutable bitmap from the source bitmap. The new bitmap may
718     * be the same object as source, or a copy may have been made.  It is
719     * initialized with the same density as the original bitmap.
720     */
721    public static Bitmap createBitmap(Bitmap src) {
722        return createBitmap(src, 0, 0, src.getWidth(), src.getHeight());
723    }
724
725    /**
726     * Returns an immutable bitmap from the specified subset of the source
727     * bitmap. The new bitmap may be the same object as source, or a copy may
728     * have been made. It is initialized with the same density as the original
729     * bitmap.
730     *
731     * @param source   The bitmap we are subsetting
732     * @param x        The x coordinate of the first pixel in source
733     * @param y        The y coordinate of the first pixel in source
734     * @param width    The number of pixels in each row
735     * @param height   The number of rows
736     * @return A copy of a subset of the source bitmap or the source bitmap itself.
737     * @throws IllegalArgumentException if the x, y, width, height values are
738     *         outside of the dimensions of the source bitmap, or width is <= 0,
739     *         or height is <= 0
740     */
741    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) {
742        return createBitmap(source, x, y, width, height, null, false);
743    }
744
745    /**
746     * Returns an immutable bitmap from subset of the source bitmap,
747     * transformed by the optional matrix. The new bitmap may be the
748     * same object as source, or a copy may have been made. It is
749     * initialized with the same density as the original bitmap.
750     *
751     * If the source bitmap is immutable and the requested subset is the
752     * same as the source bitmap itself, then the source bitmap is
753     * returned and no new bitmap is created.
754     *
755     * @param source   The bitmap we are subsetting
756     * @param x        The x coordinate of the first pixel in source
757     * @param y        The y coordinate of the first pixel in source
758     * @param width    The number of pixels in each row
759     * @param height   The number of rows
760     * @param m        Optional matrix to be applied to the pixels
761     * @param filter   true if the source should be filtered.
762     *                   Only applies if the matrix contains more than just
763     *                   translation.
764     * @return A bitmap that represents the specified subset of source
765     * @throws IllegalArgumentException if the x, y, width, height values are
766     *         outside of the dimensions of the source bitmap, or width is <= 0,
767     *         or height is <= 0
768     */
769    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
770            Matrix m, boolean filter) {
771
772        checkXYSign(x, y);
773        checkWidthHeight(width, height);
774        if (x + width > source.getWidth()) {
775            throw new IllegalArgumentException("x + width must be <= bitmap.width()");
776        }
777        if (y + height > source.getHeight()) {
778            throw new IllegalArgumentException("y + height must be <= bitmap.height()");
779        }
780
781        // check if we can just return our argument unchanged
782        if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
783                height == source.getHeight() && (m == null || m.isIdentity())) {
784            return source;
785        }
786
787        boolean isHardware = source.getConfig() == Config.HARDWARE;
788        if (isHardware) {
789            source = nativeCopyPreserveInternalConfig(source.mNativePtr);
790        }
791
792        int neww = width;
793        int newh = height;
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        RectF deviceR = new RectF();
800
801        Config newConfig = Config.ARGB_8888;
802        final Config config = source.getConfig();
803        // GIF files generate null configs, assume ARGB_8888
804        if (config != null) {
805            switch (config) {
806                case RGB_565:
807                    newConfig = Config.RGB_565;
808                    break;
809                case ALPHA_8:
810                    newConfig = Config.ALPHA_8;
811                    break;
812                case RGBA_F16:
813                    newConfig = Config.RGBA_F16;
814                    break;
815                //noinspection deprecation
816                case ARGB_4444:
817                case ARGB_8888:
818                default:
819                    newConfig = Config.ARGB_8888;
820                    break;
821            }
822        }
823
824        if (m == null || m.isIdentity()) {
825            bitmap = createBitmap(neww, newh, newConfig, source.hasAlpha());
826            paint = null;   // not needed
827        } else {
828            final boolean transformed = !m.rectStaysRect();
829
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            paint = new Paint();
844            paint.setFilterBitmap(filter);
845            if (transformed) {
846                paint.setAntiAlias(true);
847            }
848        }
849
850        // The new bitmap was created from a known bitmap source so assume that
851        // they use the same density
852        bitmap.mDensity = source.mDensity;
853        bitmap.setHasAlpha(source.hasAlpha());
854        bitmap.setPremultiplied(source.mRequestPremultiplied);
855
856        Canvas canvas = new Canvas(bitmap);
857        canvas.translate(-deviceR.left, -deviceR.top);
858        canvas.concat(m);
859        canvas.drawBitmap(source, srcR, dstR, paint);
860        canvas.setBitmap(null);
861        if (isHardware) {
862            return bitmap.copy(Config.HARDWARE, false);
863        }
864        return bitmap;
865    }
866
867    /**
868     * Returns a mutable bitmap with the specified width and height.  Its
869     * initial density is as per {@link #getDensity}.
870     *
871     * @param width    The width of the bitmap
872     * @param height   The height of the bitmap
873     * @param config   The bitmap config to create.
874     * @throws IllegalArgumentException if the width or height are <= 0, or if
875     *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
876     */
877    public static Bitmap createBitmap(int width, int height, Config config) {
878        return createBitmap(width, height, config, true);
879    }
880
881    /**
882     * Returns a mutable bitmap with the specified width and height.  Its
883     * initial density is determined from the given {@link DisplayMetrics}.
884     *
885     * @param display  Display metrics for the display this bitmap will be
886     *                 drawn on.
887     * @param width    The width of the bitmap
888     * @param height   The height of the bitmap
889     * @param config   The bitmap config to create.
890     * @throws IllegalArgumentException if the width or height are <= 0, or if
891     *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
892     */
893    public static Bitmap createBitmap(DisplayMetrics display, int width,
894            int height, Config config) {
895        return createBitmap(display, width, height, config, true);
896    }
897
898    /**
899     * Returns a mutable bitmap with the specified width and height.  Its
900     * initial density is as per {@link #getDensity}.
901     *
902     * @param width    The width of the bitmap
903     * @param height   The height of the bitmap
904     * @param config   The bitmap config to create.
905     * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
906     *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
907     *                 instead of transparent.
908     *
909     * @throws IllegalArgumentException if the width or height are <= 0, or if
910     *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
911     */
912    public static Bitmap createBitmap(int width, int height, Config config, boolean hasAlpha) {
913        return createBitmap(null, width, height, config, hasAlpha);
914    }
915
916    /**
917     * Returns a mutable bitmap with the specified width and height.  Its
918     * initial density is determined from the given {@link DisplayMetrics}.
919     *
920     * @param display  Display metrics for the display this bitmap will be
921     *                 drawn on.
922     * @param width    The width of the bitmap
923     * @param height   The height of the bitmap
924     * @param config   The bitmap config to create.
925     * @param hasAlpha If the bitmap is ARGB_8888 or RGBA_16F this flag can be used to
926     *                 mark the bitmap as opaque. Doing so will clear the bitmap in black
927     *                 instead of transparent.
928     *
929     * @throws IllegalArgumentException if the width or height are <= 0, or if
930     *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
931     */
932    public static Bitmap createBitmap(DisplayMetrics display, int width, int height,
933            Config config, boolean hasAlpha) {
934        if (width <= 0 || height <= 0) {
935            throw new IllegalArgumentException("width and height must be > 0");
936        }
937        if (config == Config.HARDWARE) {
938            throw new IllegalArgumentException("can't create mutable bitmap with Config.HARDWARE");
939        }
940        Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true);
941        if (display != null) {
942            bm.mDensity = display.densityDpi;
943        }
944        bm.setHasAlpha(hasAlpha);
945        if ((config == Config.ARGB_8888 || config == Config.RGBA_F16) && !hasAlpha) {
946            nativeErase(bm.mNativePtr, 0xff000000);
947        }
948        // No need to initialize the bitmap to zeroes with other configs;
949        // it is backed by a VM byte array which is by definition preinitialized
950        // to all zeroes.
951        return bm;
952    }
953
954    /**
955     * Returns a immutable bitmap with the specified width and height, with each
956     * pixel value set to the corresponding value in the colors array.  Its
957     * initial density is as per {@link #getDensity}.
958     *
959     * @param colors   Array of {@link Color} used to initialize the pixels.
960     * @param offset   Number of values to skip before the first color in the
961     *                 array of colors.
962     * @param stride   Number of colors in the array between rows (must be >=
963     *                 width or <= -width).
964     * @param width    The width of the bitmap
965     * @param height   The height of the bitmap
966     * @param config   The bitmap config to create. If the config does not
967     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
968     *                 bytes in the colors[] will be ignored (assumed to be FF)
969     * @throws IllegalArgumentException if the width or height are <= 0, or if
970     *         the color array's length is less than the number of pixels.
971     */
972    public static Bitmap createBitmap(int colors[], int offset, int stride,
973            int width, int height, Config config) {
974        return createBitmap(null, colors, offset, stride, width, height, config);
975    }
976
977    /**
978     * Returns a immutable bitmap with the specified width and height, with each
979     * pixel value set to the corresponding value in the colors array.  Its
980     * initial density is determined from the given {@link DisplayMetrics}.
981     *
982     * @param display  Display metrics for the display this bitmap will be
983     *                 drawn on.
984     * @param colors   Array of {@link Color} used to initialize the pixels.
985     * @param offset   Number of values to skip before the first color in the
986     *                 array of colors.
987     * @param stride   Number of colors in the array between rows (must be >=
988     *                 width or <= -width).
989     * @param width    The width of the bitmap
990     * @param height   The height of the bitmap
991     * @param config   The bitmap config to create. If the config does not
992     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
993     *                 bytes in the colors[] will be ignored (assumed to be FF)
994     * @throws IllegalArgumentException if the width or height are <= 0, or if
995     *         the color array's length is less than the number of pixels.
996     */
997    public static Bitmap createBitmap(DisplayMetrics display, int colors[],
998            int offset, int stride, int width, int height, Config config) {
999
1000        checkWidthHeight(width, height);
1001        if (Math.abs(stride) < width) {
1002            throw new IllegalArgumentException("abs(stride) must be >= width");
1003        }
1004        int lastScanline = offset + (height - 1) * stride;
1005        int length = colors.length;
1006        if (offset < 0 || (offset + width > length) || lastScanline < 0 ||
1007                (lastScanline + width > length)) {
1008            throw new ArrayIndexOutOfBoundsException();
1009        }
1010        if (width <= 0 || height <= 0) {
1011            throw new IllegalArgumentException("width and height must be > 0");
1012        }
1013        Bitmap bm = nativeCreate(colors, offset, stride, width, height,
1014                            config.nativeInt, false);
1015        if (display != null) {
1016            bm.mDensity = display.densityDpi;
1017        }
1018        return bm;
1019    }
1020
1021    /**
1022     * Returns a immutable bitmap with the specified width and height, with each
1023     * pixel value set to the corresponding value in the colors array.  Its
1024     * initial density is as per {@link #getDensity}.
1025     *
1026     * @param colors   Array of {@link Color} used to initialize the pixels.
1027     *                 This array must be at least as large as width * height.
1028     * @param width    The width of the bitmap
1029     * @param height   The height of the bitmap
1030     * @param config   The bitmap config to create. If the config does not
1031     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
1032     *                 bytes in the colors[] will be ignored (assumed to be FF)
1033     * @throws IllegalArgumentException if the width or height are <= 0, or if
1034     *         the color array's length is less than the number of pixels.
1035     */
1036    public static Bitmap createBitmap(int colors[], int width, int height, Config config) {
1037        return createBitmap(null, colors, 0, width, width, height, config);
1038    }
1039
1040    /**
1041     * Returns a immutable bitmap with the specified width and height, with each
1042     * pixel value set to the corresponding value in the colors array.  Its
1043     * initial density is determined from the given {@link DisplayMetrics}.
1044     *
1045     * @param display  Display metrics for the display this bitmap will be
1046     *                 drawn on.
1047     * @param colors   Array of {@link Color} used to initialize the pixels.
1048     *                 This array must be at least as large as width * height.
1049     * @param width    The width of the bitmap
1050     * @param height   The height of the bitmap
1051     * @param config   The bitmap config to create. If the config does not
1052     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
1053     *                 bytes in the colors[] will be ignored (assumed to be FF)
1054     * @throws IllegalArgumentException if the width or height are <= 0, or if
1055     *         the color array's length is less than the number of pixels.
1056     */
1057    public static Bitmap createBitmap(DisplayMetrics display, int colors[],
1058            int width, int height, Config config) {
1059        return createBitmap(display, colors, 0, width, width, height, config);
1060    }
1061
1062    /**
1063     * Returns an optional array of private data, used by the UI system for
1064     * some bitmaps. Not intended to be called by applications.
1065     */
1066    public byte[] getNinePatchChunk() {
1067        return mNinePatchChunk;
1068    }
1069
1070    /**
1071     * Populates a rectangle with the bitmap's optical insets.
1072     *
1073     * @param outInsets Rect to populate with optical insets
1074     * @hide
1075     */
1076    public void getOpticalInsets(@NonNull Rect outInsets) {
1077        if (mNinePatchInsets == null) {
1078            outInsets.setEmpty();
1079        } else {
1080            outInsets.set(mNinePatchInsets.opticalRect);
1081        }
1082    }
1083
1084    /** @hide */
1085    public NinePatch.InsetStruct getNinePatchInsets() {
1086        return mNinePatchInsets;
1087    }
1088
1089    /**
1090     * Specifies the known formats a bitmap can be compressed into
1091     */
1092    public enum CompressFormat {
1093        JPEG    (0),
1094        PNG     (1),
1095        WEBP    (2);
1096
1097        CompressFormat(int nativeInt) {
1098            this.nativeInt = nativeInt;
1099        }
1100        final int nativeInt;
1101    }
1102
1103    /**
1104     * Number of bytes of temp storage we use for communicating between the
1105     * native compressor and the java OutputStream.
1106     */
1107    private final static int WORKING_COMPRESS_STORAGE = 4096;
1108
1109    /**
1110     * Write a compressed version of the bitmap to the specified outputstream.
1111     * If this returns true, the bitmap can be reconstructed by passing a
1112     * corresponding inputstream to BitmapFactory.decodeStream(). Note: not
1113     * all Formats support all bitmap configs directly, so it is possible that
1114     * the returned bitmap from BitmapFactory could be in a different bitdepth,
1115     * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque
1116     * pixels).
1117     *
1118     * @param format   The format of the compressed image
1119     * @param quality  Hint to the compressor, 0-100. 0 meaning compress for
1120     *                 small size, 100 meaning compress for max quality. Some
1121     *                 formats, like PNG which is lossless, will ignore the
1122     *                 quality setting
1123     * @param stream   The outputstream to write the compressed data.
1124     * @return true if successfully compressed to the specified stream.
1125     */
1126    public boolean compress(CompressFormat format, int quality, OutputStream stream) {
1127        checkRecycled("Can't compress a recycled bitmap");
1128        // do explicit check before calling the native method
1129        if (stream == null) {
1130            throw new NullPointerException();
1131        }
1132        if (quality < 0 || quality > 100) {
1133            throw new IllegalArgumentException("quality must be 0..100");
1134        }
1135        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress");
1136        boolean result = nativeCompress(mNativePtr, format.nativeInt,
1137                quality, stream, new byte[WORKING_COMPRESS_STORAGE]);
1138        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1139        return result;
1140    }
1141
1142    /**
1143     * Returns true if the bitmap is marked as mutable (i.e.&nbsp;can be drawn into)
1144     */
1145    public final boolean isMutable() {
1146        return mIsMutable;
1147    }
1148
1149    /**
1150     * <p>Indicates whether pixels stored in this bitmaps are stored pre-multiplied.
1151     * When a pixel is pre-multiplied, the RGB components have been multiplied by
1152     * the alpha component. For instance, if the original color is a 50%
1153     * translucent red <code>(128, 255, 0, 0)</code>, the pre-multiplied form is
1154     * <code>(128, 128, 0, 0)</code>.</p>
1155     *
1156     * <p>This method always returns false if {@link #getConfig()} is
1157     * {@link Bitmap.Config#RGB_565}.</p>
1158     *
1159     * <p>The return value is undefined if {@link #getConfig()} is
1160     * {@link Bitmap.Config#ALPHA_8}.</p>
1161     *
1162     * <p>This method only returns true if {@link #hasAlpha()} returns true.
1163     * A bitmap with no alpha channel can be used both as a pre-multiplied and
1164     * as a non pre-multiplied bitmap.</p>
1165     *
1166     * <p>Only pre-multiplied bitmaps may be drawn by the view system or
1167     * {@link Canvas}. If a non-pre-multiplied bitmap with an alpha channel is
1168     * drawn to a Canvas, a RuntimeException will be thrown.</p>
1169     *
1170     * @return true if the underlying pixels have been pre-multiplied, false
1171     *         otherwise
1172     *
1173     * @see Bitmap#setPremultiplied(boolean)
1174     * @see BitmapFactory.Options#inPremultiplied
1175     */
1176    public final boolean isPremultiplied() {
1177        if (mRecycled) {
1178            Log.w(TAG, "Called isPremultiplied() on a recycle()'d bitmap! This is undefined behavior!");
1179        }
1180        return nativeIsPremultiplied(mNativePtr);
1181    }
1182
1183    /**
1184     * Sets whether the bitmap should treat its data as pre-multiplied.
1185     *
1186     * <p>Bitmaps are always treated as pre-multiplied by the view system and
1187     * {@link Canvas} for performance reasons. Storing un-pre-multiplied data in
1188     * a Bitmap (through {@link #setPixel}, {@link #setPixels}, or {@link
1189     * BitmapFactory.Options#inPremultiplied BitmapFactory.Options.inPremultiplied})
1190     * can lead to incorrect blending if drawn by the framework.</p>
1191     *
1192     * <p>This method will not affect the behavior of a bitmap without an alpha
1193     * channel, or if {@link #hasAlpha()} returns false.</p>
1194     *
1195     * <p>Calling {@link #createBitmap} or {@link #createScaledBitmap} with a source
1196     * Bitmap whose colors are not pre-multiplied may result in a RuntimeException,
1197     * since those functions require drawing the source, which is not supported for
1198     * un-pre-multiplied Bitmaps.</p>
1199     *
1200     * @see Bitmap#isPremultiplied()
1201     * @see BitmapFactory.Options#inPremultiplied
1202     */
1203    public final void setPremultiplied(boolean premultiplied) {
1204        checkRecycled("setPremultiplied called on a recycled bitmap");
1205        mRequestPremultiplied = premultiplied;
1206        nativeSetPremultiplied(mNativePtr, premultiplied);
1207    }
1208
1209    /** Returns the bitmap's width */
1210    public final int getWidth() {
1211        if (mRecycled) {
1212            Log.w(TAG, "Called getWidth() on a recycle()'d bitmap! This is undefined behavior!");
1213        }
1214        return mWidth;
1215    }
1216
1217    /** Returns the bitmap's height */
1218    public final int getHeight() {
1219        if (mRecycled) {
1220            Log.w(TAG, "Called getHeight() on a recycle()'d bitmap! This is undefined behavior!");
1221        }
1222        return mHeight;
1223    }
1224
1225    /**
1226     * Convenience for calling {@link #getScaledWidth(int)} with the target
1227     * density of the given {@link Canvas}.
1228     */
1229    public int getScaledWidth(Canvas canvas) {
1230        return scaleFromDensity(getWidth(), mDensity, canvas.mDensity);
1231    }
1232
1233    /**
1234     * Convenience for calling {@link #getScaledHeight(int)} with the target
1235     * density of the given {@link Canvas}.
1236     */
1237    public int getScaledHeight(Canvas canvas) {
1238        return scaleFromDensity(getHeight(), mDensity, canvas.mDensity);
1239    }
1240
1241    /**
1242     * Convenience for calling {@link #getScaledWidth(int)} with the target
1243     * density of the given {@link DisplayMetrics}.
1244     */
1245    public int getScaledWidth(DisplayMetrics metrics) {
1246        return scaleFromDensity(getWidth(), mDensity, metrics.densityDpi);
1247    }
1248
1249    /**
1250     * Convenience for calling {@link #getScaledHeight(int)} with the target
1251     * density of the given {@link DisplayMetrics}.
1252     */
1253    public int getScaledHeight(DisplayMetrics metrics) {
1254        return scaleFromDensity(getHeight(), mDensity, metrics.densityDpi);
1255    }
1256
1257    /**
1258     * Convenience method that returns the width of this bitmap divided
1259     * by the density scale factor.
1260     *
1261     * @param targetDensity The density of the target canvas of the bitmap.
1262     * @return The scaled width of this bitmap, according to the density scale factor.
1263     */
1264    public int getScaledWidth(int targetDensity) {
1265        return scaleFromDensity(getWidth(), mDensity, targetDensity);
1266    }
1267
1268    /**
1269     * Convenience method that returns the height of this bitmap divided
1270     * by the density scale factor.
1271     *
1272     * @param targetDensity The density of the target canvas of the bitmap.
1273     * @return The scaled height of this bitmap, according to the density scale factor.
1274     */
1275    public int getScaledHeight(int targetDensity) {
1276        return scaleFromDensity(getHeight(), mDensity, targetDensity);
1277    }
1278
1279    /**
1280     * @hide
1281     */
1282    static public int scaleFromDensity(int size, int sdensity, int tdensity) {
1283        if (sdensity == DENSITY_NONE || tdensity == DENSITY_NONE || sdensity == tdensity) {
1284            return size;
1285        }
1286
1287        // Scale by tdensity / sdensity, rounding up.
1288        return ((size * tdensity) + (sdensity >> 1)) / sdensity;
1289    }
1290
1291    /**
1292     * Return the number of bytes between rows in the bitmap's pixels. Note that
1293     * this refers to the pixels as stored natively by the bitmap. If you call
1294     * getPixels() or setPixels(), then the pixels are uniformly treated as
1295     * 32bit values, packed according to the Color class.
1296     *
1297     * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, this method
1298     * should not be used to calculate the memory usage of the bitmap. Instead,
1299     * see {@link #getAllocationByteCount()}.
1300     *
1301     * @return number of bytes between rows of the native bitmap pixels.
1302     */
1303    public final int getRowBytes() {
1304        if (mRecycled) {
1305            Log.w(TAG, "Called getRowBytes() on a recycle()'d bitmap! This is undefined behavior!");
1306        }
1307        return nativeRowBytes(mNativePtr);
1308    }
1309
1310    /**
1311     * Returns the minimum number of bytes that can be used to store this bitmap's pixels.
1312     *
1313     * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can
1314     * no longer be used to determine memory usage of a bitmap. See {@link
1315     * #getAllocationByteCount()}.</p>
1316     */
1317    public final int getByteCount() {
1318        if (mRecycled) {
1319            Log.w(TAG, "Called getByteCount() on a recycle()'d bitmap! "
1320                    + "This is undefined behavior!");
1321            return 0;
1322        }
1323        // int result permits bitmaps up to 46,340 x 46,340
1324        return getRowBytes() * getHeight();
1325    }
1326
1327    /**
1328     * Returns the size of the allocated memory used to store this bitmap's pixels.
1329     *
1330     * <p>This can be larger than the result of {@link #getByteCount()} if a bitmap is reused to
1331     * decode other bitmaps of smaller size, or by manual reconfiguration. See {@link
1332     * #reconfigure(int, int, Config)}, {@link #setWidth(int)}, {@link #setHeight(int)}, {@link
1333     * #setConfig(Bitmap.Config)}, and {@link BitmapFactory.Options#inBitmap
1334     * BitmapFactory.Options.inBitmap}. If a bitmap is not modified in this way, this value will be
1335     * the same as that returned by {@link #getByteCount()}.</p>
1336     *
1337     * <p>This value will not change over the lifetime of a Bitmap.</p>
1338     *
1339     * @see #reconfigure(int, int, Config)
1340     */
1341    public final int getAllocationByteCount() {
1342        if (mRecycled) {
1343            Log.w(TAG, "Called getAllocationByteCount() on a recycle()'d bitmap! "
1344                    + "This is undefined behavior!");
1345            return 0;
1346        }
1347        return nativeGetAllocationByteCount(mNativePtr);
1348    }
1349
1350    /**
1351     * If the bitmap's internal config is in one of the public formats, return
1352     * that config, otherwise return null.
1353     */
1354    public final Config getConfig() {
1355        if (mRecycled) {
1356            Log.w(TAG, "Called getConfig() on a recycle()'d bitmap! This is undefined behavior!");
1357        }
1358        return Config.nativeToConfig(nativeConfig(mNativePtr));
1359    }
1360
1361    /** Returns true if the bitmap's config supports per-pixel alpha, and
1362     * if the pixels may contain non-opaque alpha values. For some configs,
1363     * this is always false (e.g. RGB_565), since they do not support per-pixel
1364     * alpha. However, for configs that do, the bitmap may be flagged to be
1365     * known that all of its pixels are opaque. In this case hasAlpha() will
1366     * also return false. If a config such as ARGB_8888 is not so flagged,
1367     * it will return true by default.
1368     */
1369    public final boolean hasAlpha() {
1370        if (mRecycled) {
1371            Log.w(TAG, "Called hasAlpha() on a recycle()'d bitmap! This is undefined behavior!");
1372        }
1373        return nativeHasAlpha(mNativePtr);
1374    }
1375
1376    /**
1377     * Tell the bitmap if all of the pixels are known to be opaque (false)
1378     * or if some of the pixels may contain non-opaque alpha values (true).
1379     * Note, for some configs (e.g. RGB_565) this call is ignored, since it
1380     * does not support per-pixel alpha values.
1381     *
1382     * This is meant as a drawing hint, as in some cases a bitmap that is known
1383     * to be opaque can take a faster drawing case than one that may have
1384     * non-opaque per-pixel alpha values.
1385     */
1386    public void setHasAlpha(boolean hasAlpha) {
1387        checkRecycled("setHasAlpha called on a recycled bitmap");
1388        nativeSetHasAlpha(mNativePtr, hasAlpha, mRequestPremultiplied);
1389    }
1390
1391    /**
1392     * Indicates whether the renderer responsible for drawing this
1393     * bitmap should attempt to use mipmaps when this bitmap is drawn
1394     * scaled down.
1395     *
1396     * If you know that you are going to draw this bitmap at less than
1397     * 50% of its original size, you may be able to obtain a higher
1398     * quality
1399     *
1400     * This property is only a suggestion that can be ignored by the
1401     * renderer. It is not guaranteed to have any effect.
1402     *
1403     * @return true if the renderer should attempt to use mipmaps,
1404     *         false otherwise
1405     *
1406     * @see #setHasMipMap(boolean)
1407     */
1408    public final boolean hasMipMap() {
1409        if (mRecycled) {
1410            Log.w(TAG, "Called hasMipMap() on a recycle()'d bitmap! This is undefined behavior!");
1411        }
1412        return nativeHasMipMap(mNativePtr);
1413    }
1414
1415    /**
1416     * Set a hint for the renderer responsible for drawing this bitmap
1417     * indicating that it should attempt to use mipmaps when this bitmap
1418     * is drawn scaled down.
1419     *
1420     * If you know that you are going to draw this bitmap at less than
1421     * 50% of its original size, you may be able to obtain a higher
1422     * quality by turning this property on.
1423     *
1424     * Note that if the renderer respects this hint it might have to
1425     * allocate extra memory to hold the mipmap levels for this bitmap.
1426     *
1427     * This property is only a suggestion that can be ignored by the
1428     * renderer. It is not guaranteed to have any effect.
1429     *
1430     * @param hasMipMap indicates whether the renderer should attempt
1431     *                  to use mipmaps
1432     *
1433     * @see #hasMipMap()
1434     */
1435    public final void setHasMipMap(boolean hasMipMap) {
1436        checkRecycled("setHasMipMap called on a recycled bitmap");
1437        nativeSetHasMipMap(mNativePtr, hasMipMap);
1438    }
1439
1440    /**
1441     * Returns the color space associated with this bitmap. If the color
1442     * space is unknown, this method returns null.
1443     */
1444    @Nullable
1445    public final ColorSpace getColorSpace() {
1446        // A reconfigure can change the configuration and rgba16f is
1447        // always linear scRGB at this time
1448        if (getConfig() == Config.RGBA_F16) {
1449            // Reset the color space for potential future reconfigurations
1450            mColorSpace = null;
1451            return ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB);
1452        }
1453
1454        // Cache the color space retrieval since it can be fairly expensive
1455        if (mColorSpace == null) {
1456            if (nativeIsSRGB(mNativePtr)) {
1457                mColorSpace = ColorSpace.get(ColorSpace.Named.SRGB);
1458            } else {
1459                float[] xyz = new float[9];
1460                float[] params = new float[7];
1461
1462                boolean hasColorSpace = nativeGetColorSpace(mNativePtr, xyz, params);
1463                if (hasColorSpace) {
1464                    ColorSpace.Rgb.TransferParameters parameters =
1465                            new ColorSpace.Rgb.TransferParameters(
1466                                    params[0], params[1], params[2],
1467                                    params[3], params[4], params[5], params[6]);
1468                    ColorSpace cs = ColorSpace.match(xyz, parameters);
1469                    if (cs != null) {
1470                        mColorSpace = cs;
1471                    } else {
1472                        mColorSpace = new ColorSpace.Rgb("Unknown", xyz, parameters);
1473                    }
1474                }
1475            }
1476        }
1477
1478        return mColorSpace;
1479    }
1480
1481    /**
1482     * Fills the bitmap's pixels with the specified {@link Color}.
1483     *
1484     * @throws IllegalStateException if the bitmap is not mutable.
1485     */
1486    public void eraseColor(@ColorInt int c) {
1487        checkRecycled("Can't erase a recycled bitmap");
1488        if (!isMutable()) {
1489            throw new IllegalStateException("cannot erase immutable bitmaps");
1490        }
1491        nativeErase(mNativePtr, c);
1492    }
1493
1494    /**
1495     * Returns the {@link Color} at the specified location. Throws an exception
1496     * if x or y are out of bounds (negative or >= to the width or height
1497     * respectively). The returned color is a non-premultiplied ARGB value in
1498     * the {@link ColorSpace.Named#SRGB sRGB} color space.
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 in the
1521     * {@link ColorSpace.Named#SRGB sRGB} color space.
1522     *
1523     * @param pixels   The array to receive the bitmap's colors
1524     * @param offset   The first index to write into pixels[]
1525     * @param stride   The number of entries in pixels[] to skip between
1526     *                 rows (must be >= bitmap's width). Can be negative.
1527     * @param x        The x coordinate of the first pixel to read from
1528     *                 the bitmap
1529     * @param y        The y coordinate of the first pixel to read from
1530     *                 the bitmap
1531     * @param width    The number of pixels to read from each row
1532     * @param height   The number of rows to read
1533     *
1534     * @throws IllegalArgumentException if x, y, width, height exceed the
1535     *         bounds of the bitmap, or if abs(stride) < width.
1536     * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
1537     *         to receive the specified number of pixels.
1538     * @throws IllegalStateException if the bitmap's config is {@link Config#HARDWARE}
1539     */
1540    public void getPixels(@ColorInt int[] pixels, int offset, int stride,
1541                          int x, int y, int width, int height) {
1542        checkRecycled("Can't call getPixels() on a recycled bitmap");
1543        checkHardware("unable to getPixels(), "
1544                + "pixel access is not supported on Config#HARDWARE bitmaps");
1545        if (width == 0 || height == 0) {
1546            return; // nothing to do
1547        }
1548        checkPixelsAccess(x, y, width, height, offset, stride, pixels);
1549        nativeGetPixels(mNativePtr, pixels, offset, stride,
1550                        x, y, width, height);
1551    }
1552
1553    /**
1554     * Shared code to check for illegal arguments passed to getPixel()
1555     * or setPixel()
1556     *
1557     * @param x x coordinate of the pixel
1558     * @param y y coordinate of the pixel
1559     */
1560    private void checkPixelAccess(int x, int y) {
1561        checkXYSign(x, y);
1562        if (x >= getWidth()) {
1563            throw new IllegalArgumentException("x must be < bitmap.width()");
1564        }
1565        if (y >= getHeight()) {
1566            throw new IllegalArgumentException("y must be < bitmap.height()");
1567        }
1568    }
1569
1570    /**
1571     * Shared code to check for illegal arguments passed to getPixels()
1572     * or setPixels()
1573     *
1574     * @param x left edge of the area of pixels to access
1575     * @param y top edge of the area of pixels to access
1576     * @param width width of the area of pixels to access
1577     * @param height height of the area of pixels to access
1578     * @param offset offset into pixels[] array
1579     * @param stride number of elements in pixels[] between each logical row
1580     * @param pixels array to hold the area of pixels being accessed
1581    */
1582    private void checkPixelsAccess(int x, int y, int width, int height,
1583                                   int offset, int stride, int pixels[]) {
1584        checkXYSign(x, y);
1585        if (width < 0) {
1586            throw new IllegalArgumentException("width must be >= 0");
1587        }
1588        if (height < 0) {
1589            throw new IllegalArgumentException("height must be >= 0");
1590        }
1591        if (x + width > getWidth()) {
1592            throw new IllegalArgumentException(
1593                    "x + width must be <= bitmap.width()");
1594        }
1595        if (y + height > getHeight()) {
1596            throw new IllegalArgumentException(
1597                    "y + height must be <= bitmap.height()");
1598        }
1599        if (Math.abs(stride) < width) {
1600            throw new IllegalArgumentException("abs(stride) must be >= width");
1601        }
1602        int lastScanline = offset + (height - 1) * stride;
1603        int length = pixels.length;
1604        if (offset < 0 || (offset + width > length)
1605                || lastScanline < 0
1606                || (lastScanline + width > length)) {
1607            throw new ArrayIndexOutOfBoundsException();
1608        }
1609    }
1610
1611    /**
1612     * <p>Write the specified {@link Color} into the bitmap (assuming it is
1613     * mutable) at the x,y coordinate. The color must be a
1614     * non-premultiplied ARGB value in the {@link ColorSpace.Named#SRGB sRGB}
1615     * color space.</p>
1616     *
1617     * @param x     The x coordinate of the pixel to replace (0...width-1)
1618     * @param y     The y coordinate of the pixel to replace (0...height-1)
1619     * @param color The ARGB color to write into the bitmap
1620     *
1621     * @throws IllegalStateException if the bitmap is not mutable
1622     * @throws IllegalArgumentException if x, y are outside of the bitmap's
1623     *         bounds.
1624     */
1625    public void setPixel(int x, int y, @ColorInt int color) {
1626        checkRecycled("Can't call setPixel() on a recycled bitmap");
1627        if (!isMutable()) {
1628            throw new IllegalStateException();
1629        }
1630        checkPixelAccess(x, y);
1631        nativeSetPixel(mNativePtr, x, y, color);
1632    }
1633
1634    /**
1635     * <p>Replace pixels in the bitmap with the colors in the array. Each element
1636     * in the array is a packed int representing a non-premultiplied ARGB
1637     * {@link Color} in the {@link ColorSpace.Named#SRGB sRGB} color space.</p>
1638     *
1639     * @param pixels   The colors to write to the bitmap
1640     * @param offset   The index of the first color to read from pixels[]
1641     * @param stride   The number of colors in pixels[] to skip between rows.
1642     *                 Normally this value will be the same as the width of
1643     *                 the bitmap, but it can be larger (or negative).
1644     * @param x        The x coordinate of the first pixel to write to in
1645     *                 the bitmap.
1646     * @param y        The y coordinate of the first pixel to write to in
1647     *                 the bitmap.
1648     * @param width    The number of colors to copy from pixels[] per row
1649     * @param height   The number of rows to write to the bitmap
1650     *
1651     * @throws IllegalStateException if the bitmap is not mutable
1652     * @throws IllegalArgumentException if x, y, width, height are outside of
1653     *         the bitmap's bounds.
1654     * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
1655     *         to receive the specified number of pixels.
1656     */
1657    public void setPixels(@ColorInt int[] pixels, int offset, int stride,
1658            int x, int y, int width, int height) {
1659        checkRecycled("Can't call setPixels() on a recycled bitmap");
1660        if (!isMutable()) {
1661            throw new IllegalStateException();
1662        }
1663        if (width == 0 || height == 0) {
1664            return; // nothing to do
1665        }
1666        checkPixelsAccess(x, y, width, height, offset, stride, pixels);
1667        nativeSetPixels(mNativePtr, pixels, offset, stride,
1668                        x, y, width, height);
1669    }
1670
1671    public static final Parcelable.Creator<Bitmap> CREATOR
1672            = new Parcelable.Creator<Bitmap>() {
1673        /**
1674         * Rebuilds a bitmap previously stored with writeToParcel().
1675         *
1676         * @param p    Parcel object to read the bitmap from
1677         * @return a new bitmap created from the data in the parcel
1678         */
1679        public Bitmap createFromParcel(Parcel p) {
1680            Bitmap bm = nativeCreateFromParcel(p);
1681            if (bm == null) {
1682                throw new RuntimeException("Failed to unparcel Bitmap");
1683            }
1684            return bm;
1685        }
1686        public Bitmap[] newArray(int size) {
1687            return new Bitmap[size];
1688        }
1689    };
1690
1691    /**
1692     * No special parcel contents.
1693     */
1694    public int describeContents() {
1695        return 0;
1696    }
1697
1698    /**
1699     * Write the bitmap and its pixels to the parcel. The bitmap can be
1700     * rebuilt from the parcel by calling CREATOR.createFromParcel().
1701     *
1702     * If this bitmap is {@link Config#HARDWARE}, it may be unparceled with a different pixel
1703     * format (e.g. 565, 8888), but the content will be preserved to the best quality permitted
1704     * by the final pixel format
1705     * @param p    Parcel object to write the bitmap data into
1706     */
1707    public void writeToParcel(Parcel p, int flags) {
1708        checkRecycled("Can't parcel a recycled bitmap");
1709        if (!nativeWriteToParcel(mNativePtr, mIsMutable, mDensity, p)) {
1710            throw new RuntimeException("native writeToParcel failed");
1711        }
1712    }
1713
1714    /**
1715     * Returns a new bitmap that captures the alpha values of the original.
1716     * This may be drawn with Canvas.drawBitmap(), where the color(s) will be
1717     * taken from the paint that is passed to the draw call.
1718     *
1719     * @return new bitmap containing the alpha channel of the original bitmap.
1720     */
1721    @CheckResult
1722    public Bitmap extractAlpha() {
1723        return extractAlpha(null, null);
1724    }
1725
1726    /**
1727     * Returns a new bitmap that captures the alpha values of the original.
1728     * These values may be affected by the optional Paint parameter, which
1729     * can contain its own alpha, and may also contain a MaskFilter which
1730     * could change the actual dimensions of the resulting bitmap (e.g.
1731     * a blur maskfilter might enlarge the resulting bitmap). If offsetXY
1732     * is not null, it returns the amount to offset the returned bitmap so
1733     * that it will logically align with the original. For example, if the
1734     * paint contains a blur of radius 2, then offsetXY[] would contains
1735     * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then
1736     * drawing the original would result in the blur visually aligning with
1737     * the original.
1738     *
1739     * <p>The initial density of the returned bitmap is the same as the original's.
1740     *
1741     * @param paint Optional paint used to modify the alpha values in the
1742     *              resulting bitmap. Pass null for default behavior.
1743     * @param offsetXY Optional array that returns the X (index 0) and Y
1744     *                 (index 1) offset needed to position the returned bitmap
1745     *                 so that it visually lines up with the original.
1746     * @return new bitmap containing the (optionally modified by paint) alpha
1747     *         channel of the original bitmap. This may be drawn with
1748     *         Canvas.drawBitmap(), where the color(s) will be taken from the
1749     *         paint that is passed to the draw call.
1750     */
1751    @CheckResult
1752    public Bitmap extractAlpha(Paint paint, int[] offsetXY) {
1753        checkRecycled("Can't extractAlpha on a recycled bitmap");
1754        long nativePaint = paint != null ? paint.getNativeInstance() : 0;
1755        Bitmap bm = nativeExtractAlpha(mNativePtr, nativePaint, offsetXY);
1756        if (bm == null) {
1757            throw new RuntimeException("Failed to extractAlpha on Bitmap");
1758        }
1759        bm.mDensity = mDensity;
1760        return bm;
1761    }
1762
1763    /**
1764     *  Given another bitmap, return true if it has the same dimensions, config,
1765     *  and pixel data as this bitmap. If any of those differ, return false.
1766     *  If other is null, return false.
1767     */
1768    public boolean sameAs(Bitmap other) {
1769        checkRecycled("Can't call sameAs on a recycled bitmap!");
1770        if (this == other) return true;
1771        if (other == null) return false;
1772        if (other.isRecycled()) {
1773            throw new IllegalArgumentException("Can't compare to a recycled bitmap!");
1774        }
1775        return nativeSameAs(mNativePtr, other.mNativePtr);
1776    }
1777
1778    /**
1779     * Rebuilds any caches associated with the bitmap that are used for
1780     * drawing it. In the case of purgeable bitmaps, this call will attempt to
1781     * ensure that the pixels have been decoded.
1782     * If this is called on more than one bitmap in sequence, the priority is
1783     * given in LRU order (i.e. the last bitmap called will be given highest
1784     * priority).
1785     *
1786     * For bitmaps with no associated caches, this call is effectively a no-op,
1787     * and therefore is harmless.
1788     */
1789    public void prepareToDraw() {
1790        checkRecycled("Can't prepareToDraw on a recycled bitmap!");
1791        // Kick off an update/upload of the bitmap outside of the normal
1792        // draw path.
1793        nativePrepareToDraw(mNativePtr);
1794    }
1795
1796    /**
1797     *
1798     * @return {@link GraphicBuffer} which is internally used by hardware bitmap
1799     * @hide
1800     */
1801    public GraphicBuffer createGraphicBufferHandle() {
1802        return nativeCreateGraphicBufferHandle(mNativePtr);
1803    }
1804
1805    //////////// native methods
1806
1807    private static native Bitmap nativeCreate(int[] colors, int offset,
1808                                              int stride, int width, int height,
1809                                              int nativeConfig, boolean mutable);
1810    private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig,
1811                                            boolean isMutable);
1812    private static native Bitmap nativeCopyAshmem(long nativeSrcBitmap);
1813    private static native Bitmap nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig);
1814    private static native long nativeGetNativeFinalizer();
1815    private static native boolean nativeRecycle(long nativeBitmap);
1816    private static native void nativeReconfigure(long nativeBitmap, int width, int height,
1817                                                 int config, boolean isPremultiplied);
1818
1819    private static native boolean nativeCompress(long nativeBitmap, int format,
1820                                            int quality, OutputStream stream,
1821                                            byte[] tempStorage);
1822    private static native void nativeErase(long nativeBitmap, int color);
1823    private static native int nativeRowBytes(long nativeBitmap);
1824    private static native int nativeConfig(long nativeBitmap);
1825
1826    private static native int nativeGetPixel(long nativeBitmap, int x, int y);
1827    private static native void nativeGetPixels(long nativeBitmap, int[] pixels,
1828                                               int offset, int stride, int x, int y,
1829                                               int width, int height);
1830
1831    private static native void nativeSetPixel(long nativeBitmap, int x, int y, int color);
1832    private static native void nativeSetPixels(long nativeBitmap, int[] colors,
1833                                               int offset, int stride, int x, int y,
1834                                               int width, int height);
1835    private static native void nativeCopyPixelsToBuffer(long nativeBitmap,
1836                                                        Buffer dst);
1837    private static native void nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src);
1838    private static native int nativeGenerationId(long nativeBitmap);
1839
1840    private static native Bitmap nativeCreateFromParcel(Parcel p);
1841    // returns true on success
1842    private static native boolean nativeWriteToParcel(long nativeBitmap,
1843                                                      boolean isMutable,
1844                                                      int density,
1845                                                      Parcel p);
1846    // returns a new bitmap built from the native bitmap's alpha, and the paint
1847    private static native Bitmap nativeExtractAlpha(long nativeBitmap,
1848                                                    long nativePaint,
1849                                                    int[] offsetXY);
1850
1851    private static native boolean nativeHasAlpha(long nativeBitmap);
1852    private static native boolean nativeIsPremultiplied(long nativeBitmap);
1853    private static native void nativeSetPremultiplied(long nativeBitmap,
1854                                                      boolean isPremul);
1855    private static native void nativeSetHasAlpha(long nativeBitmap,
1856                                                 boolean hasAlpha,
1857                                                 boolean requestPremul);
1858    private static native boolean nativeHasMipMap(long nativeBitmap);
1859    private static native void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap);
1860    private static native boolean nativeSameAs(long nativeBitmap0, long nativeBitmap1);
1861    private static native void nativePrepareToDraw(long nativeBitmap);
1862    private static native int nativeGetAllocationByteCount(long nativeBitmap);
1863    private static native Bitmap nativeCopyPreserveInternalConfig(long nativeBitmap);
1864    private static native Bitmap nativeCreateHardwareBitmap(GraphicBuffer buffer);
1865    private static native GraphicBuffer nativeCreateGraphicBufferHandle(long nativeBitmap);
1866    private static native boolean nativeGetColorSpace(long nativePtr, float[] xyz, float[] params);
1867    private static native boolean nativeIsSRGB(long nativePtr);
1868}
1869