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