2011-08-04 159 views
1

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

 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

This将帮助你=)


编辑:(从链接嵌入答案)

只有静态的 “构造” 为位图返回一个可变的一个是:

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

  • 所以你可以使用getPixels/set像素或像这样:

    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); 
    
  • 如何从位图来获得绘制:使用BitmapDrawable子类延伸绘制对象,像这样:

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

这将有所帮助,但有关如何更好的更多信息。 – webLacky3rdClass

+0

你所问的所有问题都在该论坛中讨论 – Chris

+0

我想说的是你的答案被标记为可能的垃圾邮件,因为身体中的体积太小了,我查看了链接并且看到它是相关的(并且是最新的在那里),但是想给你一个正面的标记,我不是故意暗示它是错的。 – webLacky3rdClass

1

bitmap您检索是immutable,这意味着它不能被修改。尽管它没有在Canvas页面上指定该构造函数需要一个mutable位图,但它确实如此。可以使用this method