Android合并两个图像

时间:2011-08-04 15:20:42

标签: android image merge android-canvas

我想合并两个图像,然后将它们保存在Android SD卡上。一个来自摄像头,一个来自资源文件夹。问题是我得到这个错误:引起:java.lang.IllegalStateException:传递给Canvas构造函数的不可变位图。感谢。

        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();
        }

通过简单地进行此更改来管理修复它:

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

现在的问题是它不会保存图像。你知道为什么吗?

2 个答案:

答案 0 :(得分:2)

This会帮助你=)


修改(从链接中嵌入答案)

Bitmap返回可变的唯一静态“构造函数”是:

  

(类:位图)public static Bitmap createBitmap(int width,int   height,boolean hasAlpha)
  返回:具有指定宽度和高度的可变位图。

  • 所以你可以使用getPixels / setPixels或者像这样:

    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);
    
  • 如何从Bitmap获取drawable:使用扩展Drawable的BitmapDrawable-Subclass,如下所示:

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

答案 1 :(得分:1)

您要检索的bitmapimmutable,表示无法修改。虽然它没有在Canvas页面上指定构造函数需要mutable位图,但确实如此。

要创建mutable位图,您可以使用this method