Android merge two images

2019-03-01 14:48发布

问题:

I want to merge two images and then save them on the Android SDCard.One is from the camera and one from the resources folder. The problem is that i get this error: Caused by: java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor. Thanks.

        Bitmap bottomImage = BitmapFactory.decodeResource(getResources(),R.drawable.blink);
        Bitmap topImage = (Bitmap) data.getExtras().get("data");  

        // As described by Steve Pomeroy in a previous comment, 
        // use the canvas to combine them.
        // Start with the first in the constructor..
        Canvas comboImage = new Canvas(bottomImage);
        // Then draw the second on top of that
        comboImage.drawBitmap(topImage, 0f, 0f, null);

        // bottomImage is now a composite of the two. 

        // To write the file out to the SDCard:
        OutputStream os = null;

        try {
            os = new FileOutputStream("/sdcard/DCIM/Camera/" + "myNewFileName.png");
            bottomImage.compress(CompressFormat.PNG, 50, os);

            //Bitmap image.compress(CompressFormat.PNG, 50, os);
        } catch(IOException e) {
            Log.v("error saving","error saving");
            e.printStackTrace();
        }

Managed to fix it by simply doing this change:

        int w = bottomImage.getWidth();
        int h = bottomImage.getHeight(); 
        Bitmap new_image = Bitmap.createBitmap(w, h ,bottomImage.getConfig());

The problem now is that it doesn't saves the image. Do you know why?

回答1:

This will help you =)


Edit: (embed answer from link)

the only static "constructor" for Bitmap returning a mutable one is:

(Class: Bitmap) public static Bitmap createBitmap(int width, int height, boolean hasAlpha)
Returns: a mutable bitmap with the specified width and height.

  • So you could work with getPixels/setPixels or like this:

    Bitmap bitmapResult = bm.createBitmap(widthOfOld, heightOfOld, hasAlpha);
    Canvas c = new Canvas();
    c.setDevice(bitmapResult); // drawXY will result on that Bitmap
    c.drawBitmap(bitmapOld, left, top, paint);
    
  • how to get the drawable from Bitmap: by using the BitmapDrawable-Subclass which extends Drawable, like this:

    Bitmap myBitmap = BitmapFactory.decode(path);
    Drawable bd = new BitmapDrawable(myBitmap);
    


回答2:

The bitmap you are retrieving is immutable, meaning it can't be modified. Although it doesn't specify on the Canvas page that the constructor needs a mutable bitmap, it does.

To create a mutable bitmap, you can use this method.