Bitmap.java revision 2361098da3b9d9c3eeed410dc72ba62c0e9177cf
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.os.Parcel;
20import android.os.Parcelable;
21import android.util.DisplayMetrics;
22
23import java.io.OutputStream;
24import java.nio.Buffer;
25import java.nio.ByteBuffer;
26import java.nio.IntBuffer;
27import java.nio.ShortBuffer;
28
29public final class Bitmap implements Parcelable {
30
31    /**
32     * Indicates that the bitmap was created for an unknown pixel density.
33     *
34     * @see Bitmap#getDensity()
35     * @see Bitmap#setDensity(int)
36     */
37    public static final int DENSITY_NONE = 0;
38
39    /**
40     * Note:  mNativeBitmap is used by FaceDetector_jni.cpp
41     * Don't change/rename without updating FaceDetector_jni.cpp
42     *
43     * @hide
44     */
45    public final int mNativeBitmap;
46
47    /**
48     * Backing buffer for the Bitmap.
49     * Made public for quick access from drawing methods -- do NOT modify
50     * from outside this class.
51     *
52     * @hide
53     */
54    public byte[] mBuffer;
55
56    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) // Keep to finalize native resources
57    private final BitmapFinalizer mFinalizer;
58
59    private final boolean mIsMutable;
60    private byte[] mNinePatchChunk;   // may be null
61    private int mWidth = -1;
62    private int mHeight = -1;
63    private boolean mRecycled;
64
65    // Package-scoped for fast access.
66    /*package*/ int mDensity = sDefaultDensity = getDefaultDensity();
67
68    private static volatile Matrix sScaleMatrix;
69
70    private static volatile int sDefaultDensity = -1;
71
72    /**
73     * For backwards compatibility, allows the app layer to change the default
74     * density when running old apps.
75     * @hide
76     */
77    public static void setDefaultDensity(int density) {
78        sDefaultDensity = density;
79    }
80
81    /*package*/ static int getDefaultDensity() {
82        if (sDefaultDensity >= 0) {
83            return sDefaultDensity;
84        }
85        sDefaultDensity = DisplayMetrics.DENSITY_DEVICE;
86        return sDefaultDensity;
87    }
88
89    /**
90     * @noinspection UnusedDeclaration
91     */
92    /*  Private constructor that must received an already allocated native
93        bitmap int (pointer).
94
95        This can be called from JNI code.
96    */
97    private Bitmap(int nativeBitmap, byte[] buffer, boolean isMutable, byte[] ninePatchChunk,
98            int density) {
99        if (nativeBitmap == 0) {
100            throw new RuntimeException("internal error: native bitmap is 0");
101        }
102
103        mBuffer = buffer;
104        // we delete this in our finalizer
105        mNativeBitmap = nativeBitmap;
106        mFinalizer = new BitmapFinalizer(nativeBitmap);
107
108        mIsMutable = isMutable;
109        mNinePatchChunk = ninePatchChunk;
110        if (density >= 0) {
111            mDensity = density;
112        }
113    }
114
115    /**
116     * <p>Returns the density for this bitmap.</p>
117     *
118     * <p>The default density is the same density as the current display,
119     * unless the current application does not support different screen
120     * densities in which case it is
121     * {@link android.util.DisplayMetrics#DENSITY_DEFAULT}.  Note that
122     * compatibility mode is determined by the application that was initially
123     * loaded into a process -- applications that share the same process should
124     * all have the same compatibility, or ensure they explicitly set the
125     * density of their bitmaps appropriately.</p>
126     *
127     * @return A scaling factor of the default density or {@link #DENSITY_NONE}
128     *         if the scaling factor is unknown.
129     *
130     * @see #setDensity(int)
131     * @see android.util.DisplayMetrics#DENSITY_DEFAULT
132     * @see android.util.DisplayMetrics#densityDpi
133     * @see #DENSITY_NONE
134     */
135    public int getDensity() {
136        return mDensity;
137    }
138
139    /**
140     * <p>Specifies the density for this bitmap.  When the bitmap is
141     * drawn to a Canvas that also has a density, it will be scaled
142     * appropriately.</p>
143     *
144     * @param density The density scaling factor to use with this bitmap or
145     *        {@link #DENSITY_NONE} if the density is unknown.
146     *
147     * @see #getDensity()
148     * @see android.util.DisplayMetrics#DENSITY_DEFAULT
149     * @see android.util.DisplayMetrics#densityDpi
150     * @see #DENSITY_NONE
151     */
152    public void setDensity(int density) {
153        mDensity = density;
154    }
155
156    /**
157     * Sets the nine patch chunk.
158     *
159     * @param chunk The definition of the nine patch
160     *
161     * @hide
162     */
163    public void setNinePatchChunk(byte[] chunk) {
164        mNinePatchChunk = chunk;
165    }
166
167    /**
168     * Free up the memory associated with this bitmap's pixels, and mark the
169     * bitmap as "dead", meaning it will throw an exception if getPixels() or
170     * setPixels() is called, and will draw nothing. This operation cannot be
171     * reversed, so it should only be called if you are sure there are no
172     * further uses for the bitmap. This is an advanced call, and normally need
173     * not be called, since the normal GC process will free up this memory when
174     * there are no more references to this bitmap.
175     */
176    public void recycle() {
177        if (!mRecycled) {
178            mBuffer = null;
179            nativeRecycle(mNativeBitmap);
180            mNinePatchChunk = null;
181            mRecycled = true;
182        }
183    }
184
185    /**
186     * Returns true if this bitmap has been recycled. If so, then it is an error
187     * to try to access its pixels, and the bitmap will not draw.
188     *
189     * @return true if the bitmap has been recycled
190     */
191    public final boolean isRecycled() {
192        return mRecycled;
193    }
194
195    /**
196     * Returns the generation ID of this bitmap. The generation ID changes
197     * whenever the bitmap is modified. This can be used as an efficient way to
198     * check if a bitmap has changed.
199     *
200     * @return The current generation ID for this bitmap.
201     *
202     * @hide
203     */
204    public int getGenerationId() {
205        return nativeGenerationId(mNativeBitmap);
206    }
207
208    /**
209     * This is called by methods that want to throw an exception if the bitmap
210     * has already been recycled.
211     */
212    private void checkRecycled(String errorMessage) {
213        if (mRecycled) {
214            throw new IllegalStateException(errorMessage);
215        }
216    }
217
218    /**
219     * Common code for checking that x and y are >= 0
220     *
221     * @param x x coordinate to ensure is >= 0
222     * @param y y coordinate to ensure is >= 0
223     */
224    private static void checkXYSign(int x, int y) {
225        if (x < 0) {
226            throw new IllegalArgumentException("x must be >= 0");
227        }
228        if (y < 0) {
229            throw new IllegalArgumentException("y must be >= 0");
230        }
231    }
232
233    /**
234     * Common code for checking that width and height are > 0
235     *
236     * @param width  width to ensure is > 0
237     * @param height height to ensure is > 0
238     */
239    private static void checkWidthHeight(int width, int height) {
240        if (width <= 0) {
241            throw new IllegalArgumentException("width must be > 0");
242        }
243        if (height <= 0) {
244            throw new IllegalArgumentException("height must be > 0");
245        }
246    }
247
248    public enum Config {
249        // these native values must match up with the enum in SkBitmap.h
250        ALPHA_8     (2),
251        RGB_565     (4),
252        ARGB_4444   (5),
253        ARGB_8888   (6);
254
255        Config(int ni) {
256            this.nativeInt = ni;
257        }
258        final int nativeInt;
259
260        /* package */ static Config nativeToConfig(int ni) {
261            return sConfigs[ni];
262        }
263
264        private static Config sConfigs[] = {
265            null, null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888
266        };
267    }
268
269    /**
270     * Copy the bitmap's pixels into the specified buffer (allocated by the
271     * caller). An exception is thrown if the buffer is not large enough to
272     * hold all of the pixels (taking into account the number of bytes per
273     * pixel) or if the Buffer subclass is not one of the support types
274     * (ByteBuffer, ShortBuffer, IntBuffer).
275     */
276    public void copyPixelsToBuffer(Buffer dst) {
277        int elements = dst.remaining();
278        int shift;
279        if (dst instanceof ByteBuffer) {
280            shift = 0;
281        } else if (dst instanceof ShortBuffer) {
282            shift = 1;
283        } else if (dst instanceof IntBuffer) {
284            shift = 2;
285        } else {
286            throw new RuntimeException("unsupported Buffer subclass");
287        }
288
289        long bufferSize = (long)elements << shift;
290        long pixelSize = (long)getRowBytes() * getHeight();
291
292        if (bufferSize < pixelSize) {
293            throw new RuntimeException("Buffer not large enough for pixels");
294        }
295
296        nativeCopyPixelsToBuffer(mNativeBitmap, dst);
297
298        // now update the buffer's position
299        int position = dst.position();
300        position += pixelSize >> shift;
301        dst.position(position);
302    }
303
304    /**
305     * Copy the pixels from the buffer, beginning at the current position,
306     * overwriting the bitmap's pixels. The data in the buffer is not changed
307     * in any way (unlike setPixels(), which converts from unpremultipled 32bit
308     * to whatever the bitmap's native format is.
309     */
310    public void copyPixelsFromBuffer(Buffer src) {
311        checkRecycled("copyPixelsFromBuffer called on recycled bitmap");
312
313        int elements = src.remaining();
314        int shift;
315        if (src instanceof ByteBuffer) {
316            shift = 0;
317        } else if (src instanceof ShortBuffer) {
318            shift = 1;
319        } else if (src instanceof IntBuffer) {
320            shift = 2;
321        } else {
322            throw new RuntimeException("unsupported Buffer subclass");
323        }
324
325        long bufferBytes = (long)elements << shift;
326        long bitmapBytes = (long)getRowBytes() * getHeight();
327
328        if (bufferBytes < bitmapBytes) {
329            throw new RuntimeException("Buffer not large enough for pixels");
330        }
331
332        nativeCopyPixelsFromBuffer(mNativeBitmap, src);
333    }
334
335    /**
336     * Tries to make a new bitmap based on the dimensions of this bitmap,
337     * setting the new bitmap's config to the one specified, and then copying
338     * this bitmap's pixels into the new bitmap. If the conversion is not
339     * supported, or the allocator fails, then this returns NULL.  The returned
340     * bitmap initially has the same density as the original.
341     *
342     * @param config    The desired config for the resulting bitmap
343     * @param isMutable True if the resulting bitmap should be mutable (i.e.
344     *                  its pixels can be modified)
345     * @return the new bitmap, or null if the copy could not be made.
346     */
347    public Bitmap copy(Config config, boolean isMutable) {
348        checkRecycled("Can't copy a recycled bitmap");
349        Bitmap b = nativeCopy(mNativeBitmap, config.nativeInt, isMutable);
350        if (b != null) {
351            b.mDensity = mDensity;
352        }
353        return b;
354    }
355
356    /**
357     * Creates a new bitmap, scaled from an existing bitmap.
358     *
359     * @param src       The source bitmap.
360     * @param dstWidth  The new bitmap's desired width.
361     * @param dstHeight The new bitmap's desired height.
362     * @param filter    true if the source should be filtered.
363     * @return the new scaled bitmap.
364     */
365    public static Bitmap createScaledBitmap(Bitmap src, int dstWidth,
366            int dstHeight, boolean filter) {
367        Matrix m;
368        synchronized (Bitmap.class) {
369            // small pool of just 1 matrix
370            m = sScaleMatrix;
371            sScaleMatrix = null;
372        }
373
374        if (m == null) {
375            m = new Matrix();
376        }
377
378        final int width = src.getWidth();
379        final int height = src.getHeight();
380        final float sx = dstWidth  / (float)width;
381        final float sy = dstHeight / (float)height;
382        m.setScale(sx, sy);
383        Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
384
385        synchronized (Bitmap.class) {
386            // do we need to check for null? why not just assign everytime?
387            if (sScaleMatrix == null) {
388                sScaleMatrix = m;
389            }
390        }
391
392        return b;
393    }
394
395    /**
396     * Returns an immutable bitmap from the source bitmap. The new bitmap may
397     * be the same object as source, or a copy may have been made.  It is
398     * initialized with the same density as the original bitmap.
399     */
400    public static Bitmap createBitmap(Bitmap src) {
401        return createBitmap(src, 0, 0, src.getWidth(), src.getHeight());
402    }
403
404    /**
405     * Returns an immutable bitmap from the specified subset of the source
406     * bitmap. The new bitmap may be the same object as source, or a copy may
407     * have been made.  It is
408     * initialized with the same density as the original bitmap.
409     *
410     * @param source   The bitmap we are subsetting
411     * @param x        The x coordinate of the first pixel in source
412     * @param y        The y coordinate of the first pixel in source
413     * @param width    The number of pixels in each row
414     * @param height   The number of rows
415     */
416    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) {
417        return createBitmap(source, x, y, width, height, null, false);
418    }
419
420    /**
421     * Returns an immutable bitmap from subset of the source bitmap,
422     * transformed by the optional matrix.  It is
423     * initialized with the same density as the original bitmap.
424     *
425     * @param source   The bitmap we are subsetting
426     * @param x        The x coordinate of the first pixel in source
427     * @param y        The y coordinate of the first pixel in source
428     * @param width    The number of pixels in each row
429     * @param height   The number of rows
430     * @param m        Optional matrix to be applied to the pixels
431     * @param filter   true if the source should be filtered.
432     *                   Only applies if the matrix contains more than just
433     *                   translation.
434     * @return A bitmap that represents the specified subset of source
435     * @throws IllegalArgumentException if the x, y, width, height values are
436     *         outside of the dimensions of the source bitmap.
437     */
438    public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
439            Matrix m, boolean filter) {
440
441        checkXYSign(x, y);
442        checkWidthHeight(width, height);
443        if (x + width > source.getWidth()) {
444            throw new IllegalArgumentException("x + width must be <= bitmap.width()");
445        }
446        if (y + height > source.getHeight()) {
447            throw new IllegalArgumentException("y + height must be <= bitmap.height()");
448        }
449
450        // check if we can just return our argument unchanged
451        if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
452                height == source.getHeight() && (m == null || m.isIdentity())) {
453            return source;
454        }
455
456        int neww = width;
457        int newh = height;
458        Canvas canvas = new Canvas();
459        Bitmap bitmap;
460        Paint paint;
461
462        Rect srcR = new Rect(x, y, x + width, y + height);
463        RectF dstR = new RectF(0, 0, width, height);
464
465        final Config newConfig = source.getConfig() == Config.ARGB_8888 ?
466                Config.ARGB_8888 : Config.RGB_565;
467
468        if (m == null || m.isIdentity()) {
469            bitmap = createBitmap(neww, newh, newConfig, source.hasAlpha());
470            paint = null;   // not needed
471        } else {
472            final boolean transformed = !m.rectStaysRect();
473
474            RectF deviceR = new RectF();
475            m.mapRect(deviceR, dstR);
476
477            neww = Math.round(deviceR.width());
478            newh = Math.round(deviceR.height());
479
480            bitmap = createBitmap(neww, newh, transformed ? Config.ARGB_8888 : newConfig,
481                    transformed || source.hasAlpha());
482
483            canvas.translate(-deviceR.left, -deviceR.top);
484            canvas.concat(m);
485
486            paint = new Paint();
487            paint.setFilterBitmap(filter);
488            if (transformed) {
489                paint.setAntiAlias(true);
490            }
491        }
492
493        // The new bitmap was created from a known bitmap source so assume that
494        // they use the same density
495        bitmap.mDensity = source.mDensity;
496
497        canvas.setBitmap(bitmap);
498        canvas.drawBitmap(source, srcR, dstR, paint);
499
500        return bitmap;
501    }
502
503    /**
504     * Returns a mutable bitmap with the specified width and height.  Its
505     * initial density is as per {@link #getDensity}.
506     *
507     * @param width    The width of the bitmap
508     * @param height   The height of the bitmap
509     * @param config   The bitmap config to create.
510     * @throws IllegalArgumentException if the width or height are <= 0
511     */
512    public static Bitmap createBitmap(int width, int height, Config config) {
513        return createBitmap(width, height, config, true);
514    }
515
516    /**
517     * Returns a mutable bitmap with the specified width and height.  Its
518     * initial density is as per {@link #getDensity}.
519     *
520     * @param width    The width of the bitmap
521     * @param height   The height of the bitmap
522     * @param config   The bitmap config to create.
523     * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the
524     *                 bitmap as opaque. Doing so will clear the bitmap in black
525     *                 instead of transparent.
526     *
527     * @throws IllegalArgumentException if the width or height are <= 0
528     */
529    private static Bitmap createBitmap(int width, int height, Config config, boolean hasAlpha) {
530        if (width <= 0 || height <= 0) {
531            throw new IllegalArgumentException("width and height must be > 0");
532        }
533        Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true);
534        if (config == Config.ARGB_8888 && !hasAlpha) {
535            bm.eraseColor(0xff000000);
536            nativeSetHasAlpha(bm.mNativeBitmap, hasAlpha);
537        } else {
538            bm.eraseColor(0);
539        }
540        return bm;
541    }
542
543    /**
544     * Returns a immutable bitmap with the specified width and height, with each
545     * pixel value set to the corresponding value in the colors array.  Its
546     * initial density is as per {@link #getDensity}.
547     *
548     * @param colors   Array of {@link Color} used to initialize the pixels.
549     * @param offset   Number of values to skip before the first color in the
550     *                 array of colors.
551     * @param stride   Number of colors in the array between rows (must be >=
552     *                 width or <= -width).
553     * @param width    The width of the bitmap
554     * @param height   The height of the bitmap
555     * @param config   The bitmap config to create. If the config does not
556     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
557     *                 bytes in the colors[] will be ignored (assumed to be FF)
558     * @throws IllegalArgumentException if the width or height are <= 0, or if
559     *         the color array's length is less than the number of pixels.
560     */
561    public static Bitmap createBitmap(int colors[], int offset, int stride,
562            int width, int height, Config config) {
563
564        checkWidthHeight(width, height);
565        if (Math.abs(stride) < width) {
566            throw new IllegalArgumentException("abs(stride) must be >= width");
567        }
568        int lastScanline = offset + (height - 1) * stride;
569        int length = colors.length;
570        if (offset < 0 || (offset + width > length) || lastScanline < 0 ||
571                (lastScanline + width > length)) {
572            throw new ArrayIndexOutOfBoundsException();
573        }
574        if (width <= 0 || height <= 0) {
575            throw new IllegalArgumentException("width and height must be > 0");
576        }
577        return nativeCreate(colors, offset, stride, width, height,
578                            config.nativeInt, false);
579    }
580
581    /**
582     * Returns a immutable bitmap with the specified width and height, with each
583     * pixel value set to the corresponding value in the colors array.  Its
584     * initial density is as per {@link #getDensity}.
585     *
586     * @param colors   Array of {@link Color} used to initialize the pixels.
587     *                 This array must be at least as large as width * height.
588     * @param width    The width of the bitmap
589     * @param height   The height of the bitmap
590     * @param config   The bitmap config to create. If the config does not
591     *                 support per-pixel alpha (e.g. RGB_565), then the alpha
592     *                 bytes in the colors[] will be ignored (assumed to be FF)
593     * @throws IllegalArgumentException if the width or height are <= 0, or if
594     *         the color array's length is less than the number of pixels.
595     */
596    public static Bitmap createBitmap(int colors[], int width, int height, Config config) {
597        return createBitmap(colors, 0, width, width, height, config);
598    }
599
600    /**
601     * Returns an optional array of private data, used by the UI system for
602     * some bitmaps. Not intended to be called by applications.
603     */
604    public byte[] getNinePatchChunk() {
605        return mNinePatchChunk;
606    }
607
608    /**
609     * Specifies the known formats a bitmap can be compressed into
610     */
611    public enum CompressFormat {
612        JPEG    (0),
613        PNG     (1);
614
615        CompressFormat(int nativeInt) {
616            this.nativeInt = nativeInt;
617        }
618        final int nativeInt;
619    }
620
621    /**
622     * Number of bytes of temp storage we use for communicating between the
623     * native compressor and the java OutputStream.
624     */
625    private final static int WORKING_COMPRESS_STORAGE = 4096;
626
627    /**
628     * Write a compressed version of the bitmap to the specified outputstream.
629     * If this returns true, the bitmap can be reconstructed by passing a
630     * corresponding inputstream to BitmapFactory.decodeStream(). Note: not
631     * all Formats support all bitmap configs directly, so it is possible that
632     * the returned bitmap from BitmapFactory could be in a different bitdepth,
633     * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque
634     * pixels).
635     *
636     * @param format   The format of the compressed image
637     * @param quality  Hint to the compressor, 0-100. 0 meaning compress for
638     *                 small size, 100 meaning compress for max quality. Some
639     *                 formats, like PNG which is lossless, will ignore the
640     *                 quality setting
641     * @param stream   The outputstream to write the compressed data.
642     * @return true if successfully compressed to the specified stream.
643     */
644    public boolean compress(CompressFormat format, int quality, OutputStream stream) {
645        checkRecycled("Can't compress a recycled bitmap");
646        // do explicit check before calling the native method
647        if (stream == null) {
648            throw new NullPointerException();
649        }
650        if (quality < 0 || quality > 100) {
651            throw new IllegalArgumentException("quality must be 0..100");
652        }
653        return nativeCompress(mNativeBitmap, format.nativeInt, quality,
654                              stream, new byte[WORKING_COMPRESS_STORAGE]);
655    }
656
657    /**
658     * Returns true if the bitmap is marked as mutable (i.e. can be drawn into)
659     */
660    public final boolean isMutable() {
661        return mIsMutable;
662    }
663
664    /** Returns the bitmap's width */
665    public final int getWidth() {
666        return mWidth == -1 ? mWidth = nativeWidth(mNativeBitmap) : mWidth;
667    }
668
669    /** Returns the bitmap's height */
670    public final int getHeight() {
671        return mHeight == -1 ? mHeight = nativeHeight(mNativeBitmap) : mHeight;
672    }
673
674    /**
675     * Convenience for calling {@link #getScaledWidth(int)} with the target
676     * density of the given {@link Canvas}.
677     */
678    public int getScaledWidth(Canvas canvas) {
679        return scaleFromDensity(getWidth(), mDensity, canvas.mDensity);
680    }
681
682    /**
683     * Convenience for calling {@link #getScaledHeight(int)} with the target
684     * density of the given {@link Canvas}.
685     */
686    public int getScaledHeight(Canvas canvas) {
687        return scaleFromDensity(getHeight(), mDensity, canvas.mDensity);
688    }
689
690    /**
691     * Convenience for calling {@link #getScaledWidth(int)} with the target
692     * density of the given {@link DisplayMetrics}.
693     */
694    public int getScaledWidth(DisplayMetrics metrics) {
695        return scaleFromDensity(getWidth(), mDensity, metrics.densityDpi);
696    }
697
698    /**
699     * Convenience for calling {@link #getScaledHeight(int)} with the target
700     * density of the given {@link DisplayMetrics}.
701     */
702    public int getScaledHeight(DisplayMetrics metrics) {
703        return scaleFromDensity(getHeight(), mDensity, metrics.densityDpi);
704    }
705
706    /**
707     * Convenience method that returns the width of this bitmap divided
708     * by the density scale factor.
709     *
710     * @param targetDensity The density of the target canvas of the bitmap.
711     * @return The scaled width of this bitmap, according to the density scale factor.
712     */
713    public int getScaledWidth(int targetDensity) {
714        return scaleFromDensity(getWidth(), mDensity, targetDensity);
715    }
716
717    /**
718     * Convenience method that returns the height of this bitmap divided
719     * by the density scale factor.
720     *
721     * @param targetDensity The density of the target canvas of the bitmap.
722     * @return The scaled height of this bitmap, according to the density scale factor.
723     */
724    public int getScaledHeight(int targetDensity) {
725        return scaleFromDensity(getHeight(), mDensity, targetDensity);
726    }
727
728    /**
729     * @hide
730     */
731    static public int scaleFromDensity(int size, int sdensity, int tdensity) {
732        if (sdensity == DENSITY_NONE || sdensity == tdensity) {
733            return size;
734        }
735
736        // Scale by tdensity / sdensity, rounding up.
737        return ( (size * tdensity) + (sdensity >> 1) ) / sdensity;
738    }
739
740    /**
741     * Return the number of bytes between rows in the bitmap's pixels. Note that
742     * this refers to the pixels as stored natively by the bitmap. If you call
743     * getPixels() or setPixels(), then the pixels are uniformly treated as
744     * 32bit values, packed according to the Color class.
745     *
746     * @return number of bytes between rows of the native bitmap pixels.
747     */
748    public final int getRowBytes() {
749        return nativeRowBytes(mNativeBitmap);
750    }
751
752    /**
753     * If the bitmap's internal config is in one of the public formats, return
754     * that config, otherwise return null.
755     */
756    public final Config getConfig() {
757        return Config.nativeToConfig(nativeConfig(mNativeBitmap));
758    }
759
760    /** Returns true if the bitmap's config supports per-pixel alpha, and
761     * if the pixels may contain non-opaque alpha values. For some configs,
762     * this is always false (e.g. RGB_565), since they do not support per-pixel
763     * alpha. However, for configs that do, the bitmap may be flagged to be
764     * known that all of its pixels are opaque. In this case hasAlpha() will
765     * also return false. If a config such as ARGB_8888 is not so flagged,
766     * it will return true by default.
767     */
768    public final boolean hasAlpha() {
769        return nativeHasAlpha(mNativeBitmap);
770    }
771
772    /**
773     * Tell the bitmap if all of the pixels are known to be opaque (false)
774     * or if some of the pixels may contain non-opaque alpha values (true).
775     * Note, for some configs (e.g. RGB_565) this call is ignore, since it does
776     * not support per-pixel alpha values.
777     *
778     * This is meant as a drawing hint, as in some cases a bitmap that is known
779     * to be opaque can take a faster drawing case than one that may have
780     * non-opaque per-pixel alpha values.
781     *
782     * @hide
783     */
784    public void setHasAlpha(boolean hasAlpha) {
785        nativeSetHasAlpha(mNativeBitmap, hasAlpha);
786    }
787
788    /**
789     * Fills the bitmap's pixels with the specified {@link Color}.
790     *
791     * @throws IllegalStateException if the bitmap is not mutable.
792     */
793    public void eraseColor(int c) {
794        checkRecycled("Can't erase a recycled bitmap");
795        if (!isMutable()) {
796            throw new IllegalStateException("cannot erase immutable bitmaps");
797        }
798        nativeErase(mNativeBitmap, c);
799    }
800
801    /**
802     * Returns the {@link Color} at the specified location. Throws an exception
803     * if x or y are out of bounds (negative or >= to the width or height
804     * respectively).
805     *
806     * @param x    The x coordinate (0...width-1) of the pixel to return
807     * @param y    The y coordinate (0...height-1) of the pixel to return
808     * @return     The argb {@link Color} at the specified coordinate
809     * @throws IllegalArgumentException if x, y exceed the bitmap's bounds
810     */
811    public int getPixel(int x, int y) {
812        checkRecycled("Can't call getPixel() on a recycled bitmap");
813        checkPixelAccess(x, y);
814        return nativeGetPixel(mNativeBitmap, x, y);
815    }
816
817    /**
818     * Returns in pixels[] a copy of the data in the bitmap. Each value is
819     * a packed int representing a {@link Color}. The stride parameter allows
820     * the caller to allow for gaps in the returned pixels array between
821     * rows. For normal packed results, just pass width for the stride value.
822     *
823     * @param pixels   The array to receive the bitmap's colors
824     * @param offset   The first index to write into pixels[]
825     * @param stride   The number of entries in pixels[] to skip between
826     *                 rows (must be >= bitmap's width). Can be negative.
827     * @param x        The x coordinate of the first pixel to read from
828     *                 the bitmap
829     * @param y        The y coordinate of the first pixel to read from
830     *                 the bitmap
831     * @param width    The number of pixels to read from each row
832     * @param height   The number of rows to read
833     * @throws IllegalArgumentException if x, y, width, height exceed the
834     *         bounds of the bitmap, or if abs(stride) < width.
835     * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
836     *         to receive the specified number of pixels.
837     */
838    public void getPixels(int[] pixels, int offset, int stride,
839                          int x, int y, int width, int height) {
840        checkRecycled("Can't call getPixels() on a recycled bitmap");
841        if (width == 0 || height == 0) {
842            return; // nothing to do
843        }
844        checkPixelsAccess(x, y, width, height, offset, stride, pixels);
845        nativeGetPixels(mNativeBitmap, pixels, offset, stride,
846                        x, y, width, height);
847    }
848
849    /**
850     * Shared code to check for illegal arguments passed to getPixel()
851     * or setPixel()
852     * @param x x coordinate of the pixel
853     * @param y y coordinate of the pixel
854     */
855    private void checkPixelAccess(int x, int y) {
856        checkXYSign(x, y);
857        if (x >= getWidth()) {
858            throw new IllegalArgumentException("x must be < bitmap.width()");
859        }
860        if (y >= getHeight()) {
861            throw new IllegalArgumentException("y must be < bitmap.height()");
862        }
863    }
864
865    /**
866     * Shared code to check for illegal arguments passed to getPixels()
867     * or setPixels()
868     *
869     * @param x left edge of the area of pixels to access
870     * @param y top edge of the area of pixels to access
871     * @param width width of the area of pixels to access
872     * @param height height of the area of pixels to access
873     * @param offset offset into pixels[] array
874     * @param stride number of elements in pixels[] between each logical row
875     * @param pixels array to hold the area of pixels being accessed
876    */
877    private void checkPixelsAccess(int x, int y, int width, int height,
878                                   int offset, int stride, int pixels[]) {
879        checkXYSign(x, y);
880        if (width < 0) {
881            throw new IllegalArgumentException("width must be >= 0");
882        }
883        if (height < 0) {
884            throw new IllegalArgumentException("height must be >= 0");
885        }
886        if (x + width > getWidth()) {
887            throw new IllegalArgumentException(
888                    "x + width must be <= bitmap.width()");
889        }
890        if (y + height > getHeight()) {
891            throw new IllegalArgumentException(
892                    "y + height must be <= bitmap.height()");
893        }
894        if (Math.abs(stride) < width) {
895            throw new IllegalArgumentException("abs(stride) must be >= width");
896        }
897        int lastScanline = offset + (height - 1) * stride;
898        int length = pixels.length;
899        if (offset < 0 || (offset + width > length)
900                || lastScanline < 0
901                || (lastScanline + width > length)) {
902            throw new ArrayIndexOutOfBoundsException();
903        }
904    }
905
906    /**
907     * Write the specified {@link Color} into the bitmap (assuming it is
908     * mutable) at the x,y coordinate.
909     *
910     * @param x     The x coordinate of the pixel to replace (0...width-1)
911     * @param y     The y coordinate of the pixel to replace (0...height-1)
912     * @param color The {@link Color} to write into the bitmap
913     * @throws IllegalStateException if the bitmap is not mutable
914     * @throws IllegalArgumentException if x, y are outside of the bitmap's
915     *         bounds.
916     */
917    public void setPixel(int x, int y, int color) {
918        checkRecycled("Can't call setPixel() on a recycled bitmap");
919        if (!isMutable()) {
920            throw new IllegalStateException();
921        }
922        checkPixelAccess(x, y);
923        nativeSetPixel(mNativeBitmap, x, y, color);
924    }
925
926    /**
927     * Replace pixels in the bitmap with the colors in the array. Each element
928     * in the array is a packed int prepresenting a {@link Color}
929     *
930     * @param pixels   The colors to write to the bitmap
931     * @param offset   The index of the first color to read from pixels[]
932     * @param stride   The number of colors in pixels[] to skip between rows.
933     *                 Normally this value will be the same as the width of
934     *                 the bitmap, but it can be larger (or negative).
935     * @param x        The x coordinate of the first pixel to write to in
936     *                 the bitmap.
937     * @param y        The y coordinate of the first pixel to write to in
938     *                 the bitmap.
939     * @param width    The number of colors to copy from pixels[] per row
940     * @param height   The number of rows to write to the bitmap
941     * @throws IllegalStateException if the bitmap is not mutable
942     * @throws IllegalArgumentException if x, y, width, height are outside of
943     *         the bitmap's bounds.
944     * @throws ArrayIndexOutOfBoundsException if the pixels array is too small
945     *         to receive the specified number of pixels.
946     */
947    public void setPixels(int[] pixels, int offset, int stride,
948                          int x, int y, int width, int height) {
949        checkRecycled("Can't call setPixels() on a recycled bitmap");
950        if (!isMutable()) {
951            throw new IllegalStateException();
952        }
953        if (width == 0 || height == 0) {
954            return; // nothing to do
955        }
956        checkPixelsAccess(x, y, width, height, offset, stride, pixels);
957        nativeSetPixels(mNativeBitmap, pixels, offset, stride,
958                        x, y, width, height);
959    }
960
961    public static final Parcelable.Creator<Bitmap> CREATOR
962            = new Parcelable.Creator<Bitmap>() {
963        /**
964         * Rebuilds a bitmap previously stored with writeToParcel().
965         *
966         * @param p    Parcel object to read the bitmap from
967         * @return a new bitmap created from the data in the parcel
968         */
969        public Bitmap createFromParcel(Parcel p) {
970            Bitmap bm = nativeCreateFromParcel(p);
971            if (bm == null) {
972                throw new RuntimeException("Failed to unparcel Bitmap");
973            }
974            return bm;
975        }
976        public Bitmap[] newArray(int size) {
977            return new Bitmap[size];
978        }
979    };
980
981    /**
982     * No special parcel contents.
983     */
984    public int describeContents() {
985        return 0;
986    }
987
988    /**
989     * Write the bitmap and its pixels to the parcel. The bitmap can be
990     * rebuilt from the parcel by calling CREATOR.createFromParcel().
991     * @param p    Parcel object to write the bitmap data into
992     */
993    public void writeToParcel(Parcel p, int flags) {
994        checkRecycled("Can't parcel a recycled bitmap");
995        if (!nativeWriteToParcel(mNativeBitmap, mIsMutable, mDensity, p)) {
996            throw new RuntimeException("native writeToParcel failed");
997        }
998    }
999
1000    /**
1001     * Returns a new bitmap that captures the alpha values of the original.
1002     * This may be drawn with Canvas.drawBitmap(), where the color(s) will be
1003     * taken from the paint that is passed to the draw call.
1004     *
1005     * @return new bitmap containing the alpha channel of the original bitmap.
1006     */
1007    public Bitmap extractAlpha() {
1008        return extractAlpha(null, null);
1009    }
1010
1011    /**
1012     * Returns a new bitmap that captures the alpha values of the original.
1013     * These values may be affected by the optional Paint parameter, which
1014     * can contain its own alpha, and may also contain a MaskFilter which
1015     * could change the actual dimensions of the resulting bitmap (e.g.
1016     * a blur maskfilter might enlarge the resulting bitmap). If offsetXY
1017     * is not null, it returns the amount to offset the returned bitmap so
1018     * that it will logically align with the original. For example, if the
1019     * paint contains a blur of radius 2, then offsetXY[] would contains
1020     * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then
1021     * drawing the original would result in the blur visually aligning with
1022     * the original.
1023     *
1024     * <p>The initial density of the returned bitmap is the same as the original's.
1025     *
1026     * @param paint Optional paint used to modify the alpha values in the
1027     *              resulting bitmap. Pass null for default behavior.
1028     * @param offsetXY Optional array that returns the X (index 0) and Y
1029     *                 (index 1) offset needed to position the returned bitmap
1030     *                 so that it visually lines up with the original.
1031     * @return new bitmap containing the (optionally modified by paint) alpha
1032     *         channel of the original bitmap. This may be drawn with
1033     *         Canvas.drawBitmap(), where the color(s) will be taken from the
1034     *         paint that is passed to the draw call.
1035     */
1036    public Bitmap extractAlpha(Paint paint, int[] offsetXY) {
1037        checkRecycled("Can't extractAlpha on a recycled bitmap");
1038        int nativePaint = paint != null ? paint.mNativePaint : 0;
1039        Bitmap bm = nativeExtractAlpha(mNativeBitmap, nativePaint, offsetXY);
1040        if (bm == null) {
1041            throw new RuntimeException("Failed to extractAlpha on Bitmap");
1042        }
1043        bm.mDensity = mDensity;
1044        return bm;
1045    }
1046
1047    /**
1048     *  Given another bitmap, return true if it has the same dimensions, config,
1049     *  and pixel data as this bitmap. If any of those differ, return false.
1050     *  If other is null, return false.
1051     *
1052     * @hide (just needed internally right now)
1053     */
1054    public boolean sameAs(Bitmap other) {
1055        return this == other ||
1056              (other != null &&
1057               nativeSameAs(mNativeBitmap, other.mNativeBitmap));
1058    }
1059
1060    /**
1061     * Rebuilds any caches associated with the bitmap that are used for
1062     * drawing it. In the case of purgeable bitmaps, this call will attempt to
1063     * ensure that the pixels have been decoded.
1064     * If this is called on more than one bitmap in sequence, the priority is
1065     * given in LRU order (i.e. the last bitmap called will be given highest
1066     * priority).
1067     *
1068     * For bitmaps with no associated caches, this call is effectively a no-op,
1069     * and therefore is harmless.
1070     */
1071    public void prepareToDraw() {
1072        nativePrepareToDraw(mNativeBitmap);
1073    }
1074
1075    private static class BitmapFinalizer {
1076        private final int mNativeBitmap;
1077
1078        BitmapFinalizer(int nativeBitmap) {
1079            mNativeBitmap = nativeBitmap;
1080        }
1081
1082        @Override
1083        public void finalize() {
1084            nativeDestructor(mNativeBitmap);
1085        }
1086    }
1087
1088    //////////// native methods
1089
1090    private static native Bitmap nativeCreate(int[] colors, int offset,
1091                                              int stride, int width, int height,
1092                                            int nativeConfig, boolean mutable);
1093    private static native Bitmap nativeCopy(int srcBitmap, int nativeConfig,
1094                                            boolean isMutable);
1095    private static native void nativeDestructor(int nativeBitmap);
1096    private static native void nativeRecycle(int nativeBitmap);
1097
1098    private static native boolean nativeCompress(int nativeBitmap, int format,
1099                                            int quality, OutputStream stream,
1100                                            byte[] tempStorage);
1101    private static native void nativeErase(int nativeBitmap, int color);
1102    private static native int nativeWidth(int nativeBitmap);
1103    private static native int nativeHeight(int nativeBitmap);
1104    private static native int nativeRowBytes(int nativeBitmap);
1105    private static native int nativeConfig(int nativeBitmap);
1106    private static native boolean nativeHasAlpha(int nativeBitmap);
1107
1108    private static native int nativeGetPixel(int nativeBitmap, int x, int y);
1109    private static native void nativeGetPixels(int nativeBitmap, int[] pixels,
1110                                               int offset, int stride, int x,
1111                                               int y, int width, int height);
1112
1113    private static native void nativeSetPixel(int nativeBitmap, int x, int y,
1114                                              int color);
1115    private static native void nativeSetPixels(int nativeBitmap, int[] colors,
1116                                               int offset, int stride, int x,
1117                                               int y, int width, int height);
1118    private static native void nativeCopyPixelsToBuffer(int nativeBitmap,
1119                                                        Buffer dst);
1120    private static native void nativeCopyPixelsFromBuffer(int nb, Buffer src);
1121    private static native int nativeGenerationId(int nativeBitmap);
1122
1123    private static native Bitmap nativeCreateFromParcel(Parcel p);
1124    // returns true on success
1125    private static native boolean nativeWriteToParcel(int nativeBitmap,
1126                                                      boolean isMutable,
1127                                                      int density,
1128                                                      Parcel p);
1129    // returns a new bitmap built from the native bitmap's alpha, and the paint
1130    private static native Bitmap nativeExtractAlpha(int nativeBitmap,
1131                                                    int nativePaint,
1132                                                    int[] offsetXY);
1133
1134    private static native void nativePrepareToDraw(int nativeBitmap);
1135    private static native void nativeSetHasAlpha(int nBitmap, boolean hasAlpha);
1136    private static native boolean nativeSameAs(int nb0, int nb1);
1137
1138    /* package */ final int ni() {
1139        return mNativeBitmap;
1140    }
1141}
1142