2011-08-04 160 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