有時候會遇到這樣的需求,將兩個bitmap對象整合並保存爲一張圖片,代碼以下:this
private Bitmap toConformBitmap(Bitmap background, Bitmap foreground) { if( background == null ) { return null; } int bgWidth = background.getWidth(); int bgHeight = background.getHeight(); //int fgWidth = foreground.getWidth(); //int fgHeight = foreground.getHeight(); //create the new blank bitmap 建立一個新的和SRC長度寬度同樣的位圖 Bitmap newbmp = Bitmap.createBitmap(bgWidth, bgHeight, Config.ARGB_8888); Canvas cv = new Canvas(newbmp); //draw bg into cv.drawBitmap(background, 0, 0, null);//在 0,0座標開始畫入bg //draw fg into cv.drawBitmap(foreground, 0, 0, null);//在 0,0座標開始畫入fg ,能夠從任意位置畫入 //save all clip cv.save(Canvas.ALL_SAVE_FLAG);//保存 //store cv.restore();//存儲 return newbmp; }
此方法分別傳入兩個bitmap對象,一個爲底圖(背景圖background),另外一個則位於其上面(前景圖foreground),若上面的bitmap是不透明的話,就會徹底遮住下面的bitmap,那麼保存爲圖片後,就只能看到位於上面的bitmap的信息,圖片的大小爲兩個bitmap疊加的大小。
保存bitmap爲一張圖片:spa
private String saveBitmap(Bitmap bitmap) { String imagePath = getApplication().getFilesDir().getAbsolutePath() + "/temp.png"; File file = new File(imagePath); if(file.exists()) { file.delete(); } try{ FileOutputStream out = new FileOutputStream(file); if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){ out.flush(); out.close(); } } catch (Exception e) { Toast.makeText(this, "保存失敗, 1).show(); e.printStackTrace(); } return imagePath; }