android整合兩個bitmap

有時候會遇到這樣的需求,將兩個bitmap對象整合並保存爲一張圖片,代碼如下:
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爲一張圖片:
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;

    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章