Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 多媒體實戰(四):用 Matrix、ColorMatrix 與 Xfermode 打造圖片編輯器

編輯:Android 開發實例

Android 的圖片處理能力,幾乎全集中在四個類手上:Bitmap 是像素本身,Canvas 是畫布,Paint 是畫筆,Matrix 與 ColorMatrix 則是兩個負責變形與調色的矩陣。本文用一個完整範例把縮放、旋轉、亮度飽和度調整、雙圖合成四件事串起來。

一、先從相簿挑兩張圖

不必自己寫檔案瀏覽器,Android 內建的 Gallery 就是現成的媒體管理員。用 Intent.ACTION_PICK 搭配 MediaStore.Images.Media.EXTERNAL_CONTENT_URI 叫它出來,使用者選完之後,回傳 Intent 的 Data 欄位就是所選圖片的 Uri。範例用 FIRST_PIC 與 SECOND_PIC 兩個 requestCode 區分先後挑選的兩張圖。

二、複製一張圖:Bitmap + Canvas + Paint

「複製」聽起來簡單,實作卻是後面所有操作的地基。手勢是這樣的:先 Bitmap.createBitmap() 開一張與原圖同尺寸、同色彩配置的空白畫布,再用它建一個 Canvas,最後 drawBitmap() 把原圖畫上去。

關鍵在於 createBitmap() 回傳的是一個可變的 Bitmap 物件——從 Uri 直接解碼出來的圖往往不可變,任何變形與調色都會失敗。這一步不能省。

範例把這個邏輯做成兩個重載:getDstImage(Matrix) 使用預設 Paint,getDstImage(Matrix, Paint) 則允許傳入自訂畫筆,供調色時使用。

三、矩陣變形:Matrix 是怎麼運作的

Matrix 是一個 3×3 矩陣,螢幕上每個像素座標由 x、y、z 三元組成,矩陣的每一行分別決定對應軸向的結果:

------------------------
 cosX   -sinX   translateX
 sinX    cosX   translateY
 0       0      scale
------------------------

x' = 1*x + 0*y + 0*z
y' = 0*x + 1*y + 0*z
z' = 0*x + 0*y + 1*z

自己填矩陣再呼叫 setValues() 是可行的,但官方並不鼓勵。Matrix 已針對常見變換提供 pre/set/post 三組方法:pre 是前乘、set 是直接設定、post 是後乘,多個變換疊加時,乘法的順序會直接影響最終結果,這一點實務上最容易出錯。

private Bitmap transferImage(){
    Matrix matrix = new Matrix();
    matrix.setValues(new float[]{
            .5f, 0, 0,     // 只影響 x 軸,圖片寬度變成原來的一半
            0, 1, 0,
            0, 0, 1
    });
    return this.getDstImage(matrix);
}

四、調色:ColorMatrix 的 4×5 矩陣

ColorMatrix 比 Matrix 多一欄,是 4 列 5 行的結構,每一列分別對應 R、G、B、A 四個通道:

-------------------------
 a1  b1  c1  d1  e1
 a2  b2  c2  d2  e2
 a3  b3  c3  d3  e3
 a4  b4  c4  d4  e4
-------------------------

R' = a1*R + b1*G + c1*B + d1*A + e1
G' = a2*R + b2*G + c2*B + d2*A + e2
B' = a3*R + b3*G + c3*B + d3*A + e3
A' = a4*R + b4*G + c4*B + d4*A + e4

看懂這個結構,調色就只是算術。前四欄是各通道的權重,最後一欄 e 是常數偏移——想整體調亮或壓暗,改這一格最有效;想讓紅色加倍,把 a1 從 1 改成 2 即可。

改好之後,ColorMatrix 必須先包裝成 ColorMatrixColorFilter,再透過 Paint.setColorFilter() 掛到畫筆上才會生效。ColorMatrix 也貼心地提供了 setSaturation()、setScale() 等便捷方法,不必凡事手算。

private Bitmap ajustImage(){
    ColorMatrix cMatrix = new ColorMatrix();

    // 手寫版本的亮度/倍率調整:
    // int brightIndex = -25;
    // int doubleColor = 2;
    // cMatrix.set(new float[]{
    //         doubleColor, 0, 0, 0, brightIndex,
    //         0, doubleColor, 0, 0, brightIndex,
    //         0, 0, doubleColor, 0, brightIndex,
    //         0, 0, 0, doubleColor, 0
    // });

    // cMatrix.setSaturation(2.0f);      // 提高飽和度
    cMatrix.setScale(2.0f, 2.0f, 2.0f, 2.0f);   // 四通道整體縮放

    Paint paint = new Paint();
    paint.setColorFilter(new ColorMatrixColorFilter(cMatrix));
    return this.getDstImage(null, paint);
}

五、合成:PorterDuff.Mode 決定疊加規則

兩張圖疊在一起,怎麼疊?答案寫在 PorterDuff.Mode 這個列舉裡。所有 Xfermode 都繼承自 Xfermode,最常用的是 PorterDuffXfermode,它把 PorterDuff 定義的一組規則套用到繪製行為上。常見模式包含 MULTIPLY(像素相乘後除以 255,畫面變暗)、SCREEN(效果相反,變亮)、LIGHTEN 與 DARKEN 等。

做法是:先照一般方式畫上第一張圖,然後在畫第二張圖之前,替 Paint 指定 Xfermode。

private Bitmap compositeImages(){
    Bitmap bmp = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());
    Paint paint = new Paint();
    Canvas canvas = new Canvas(bmp);

    // 第一張:照原樣畫上去
    canvas.drawBitmap(srcBitmap, 0, 0, paint);

    // 第二張:指定 MULTIPLY 模式,兩圖對應像素相乘後除以 255
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
    canvas.drawBitmap(dstBitmap, 0, 0, paint);

    return bmp;
}

六、大圖記得先降採樣

手機相拍的照片動輒數百萬像素,直接 decodeStream() 進記憶體極易引發 OutOfMemoryError。標準解法是兩段式解碼:第一次把 inJustDecodeBounds 設為 true,只讀取圖片尺寸而不配置像素記憶體;算出縮放比例塞進 inSampleSize;第二次才正式解碼。

private Bitmap getSrcImage(Uri imageUri){
    try {
        BitmapFactory.Options ops = new BitmapFactory.Options();
        ops.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeStream(
                this.getContentResolver().openInputStream(imageUri), null, ops);

        int wRatio = (int)Math.ceil(ops.outWidth  / (float)MAX_WIDTH);
        int hRatio = (int)Math.ceil(ops.outHeight / (float)MAX_HEIGHT);

        if(wRatio > 1 && hRatio > 1){
            ops.inSampleSize = (wRatio > hRatio) ? wRatio : hRatio;
        }

        ops.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(
                this.getContentResolver().openInputStream(imageUri), null, ops);
        return bmp;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e(this.getClass().getName(), e.getMessage());
    }
    return null;
}

七、把功能掛到選單上

最後用 onCreateOptionsMenu() 掛上「複製/變換/亮度/合成」四個選項,在 onOptionsItemSelected() 裡依序呼叫對應方法,再把結果塞回右側的 ImageView:

public boolean onCreateOptionsMenu(Menu menu){
    menu.add(Menu.NONE, 1, Menu.NONE, "複制");
    menu.add(Menu.NONE, 2, Menu.NONE, "變換");
    menu.add(Menu.NONE, 3, Menu.NONE, "亮度");
    menu.add(Menu.NONE, 4, Menu.NONE, "合成");
    return super.onCreateOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item){
    switch(item.getItemId()){
        case 1:  // 複製
            if(srcBitmap != null){
                dstBitmap = getDstImage(null);
                dstImageView.setImageBitmap(dstBitmap);
            }
            break;
        case 2:  // 變形
            if(srcBitmap != null){
                dstBitmap = transferImage();
                dstImageView.setImageBitmap(dstBitmap);
            }
            break;
        case 3:  // 調色
            if(srcBitmap != null){
                dstBitmap = ajustImage();
                dstImageView.setImageBitmap(dstBitmap);
            }
            break;
        case 4:  // 合成
            if(srcBitmap != null && dstBitmap != null){
                dstBitmap = compositeImages();
                dstImageView.setImageBitmap(dstBitmap);
            }
            break;
    }
    return true;
}

八、一個必須修正的邏輯瑕疵

原始碼裡有個不容易察覺的 bug:getDstImage() 在 matrix != null 的分支中呼叫的是 canvas.drawBitmap(dstBitmap, matrix, paint),但此時 dstBitmap 還是一張剛建立、尚未畫上任何內容的空白圖——應該要畫的是 srcBitmap。照原樣執行,套用矩陣變形後只會得到一片空白。把該行改成 canvas.drawBitmap(srcBitmap, matrix, paint) 才是正確行為。

另外,onActivityResult() 的呼叫端最好加上 requestCode 與 resultCode 的防禦性判斷,並在離開頁面時呼叫 Bitmap.recycle() 釋放大型圖片佔用的記憶體,這在記憶體受限的舊機型上是必要的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved