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