Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Bitmap 加載優化與逐像素加工實戰

編輯:關於 Android 程式設計

一、載入與像素讀寫

Android SDK 提供了 getPixel 與 setPixel 兩個 API 讓我們直接操作像素。讀取的寫法如下:

int pixel = bitmap.getPixel(col, row);   // ARGB
int red   = Color.red(pixel);            // 等同 (pixel >> 16) & 0xff
int green = Color.green(pixel);          // 等同 (pixel >> 8) & 0xff
int blue  = Color.blue(pixel);           // 等同 pixel & 0xff
int alpha = Color.alpha(pixel);          // 等同 pixel >>> 24

取回的 pixel 是一個 32 位元整數,四個位元組剛好對應透明通道與紅、綠、藍三個色彩通道。寫入的時候則用 Color.argb 反向組裝回去:

bm.setPixel(col, row, Color.argb(alpha, red, green, blue));

為什麼大圖會 OOM,以及怎麼避開

使用 BitmapFactory.decodeFile 或 decodeResource 這類方法載入圖片時,这些方法會直接為 Bitmap 配置好對應大小的記憶體。若原始圖檔解析後的像素量過大,DVM 無法分配所請求的記憶體,就會拋出 OOM。

解法是先在「不真正解碼像素」的前提下讀出圖片的寬高,据此決定要不要縮小取樣。關鍵在 inJustDecodeBounds:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.shar_03, options);
int height = options.outHeight;
int width = options.outWidth;
String imageType = options.outMimeType;

接著計算合適的 inSampleSize。慣例是取 2 的幂,並確保縮小後的寬高仍大於目標尺寸:

int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
    final int halfHeight = height / 2;
    final int halfWidth = width / 2;
    while ((halfHeight / inSampleSize) > reqHeight
            && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
srcImage = BitmapFactory.decodeResource(getResources(), R.drawable.shar_03, options);

二、像素級加工

彩色轉灰度的三種公式

最常見的圖像處理莫過於去色。三種常用算法的差別在於權重:

  • 方法一(最大值平均值法):GRAY = (max(R,G,B) + min(R,G,B)) / 2
  • 方法二(等權平均法):GRAY = (R + G + B) / 3
  • 方法三(加權法,最貼近人眼感知):GRAY = R × 0.3 + G × 0.59 + B × 0.11
public Bitmap gray(Bitmap bitmap, int schema) {
    Bitmap bm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            int pixel = bitmap.getPixel(col, row);
            int red = Color.red(pixel);
            int green = Color.green(pixel);
            int blue = Color.blue(pixel);
            int alpha = Color.alpha(pixel);

            int gray = 0;
            if (schema == 0) {
                gray = (Math.max(blue, Math.max(red, green))
                        + Math.min(blue, Math.min(red, green))) / 2;
            } else if (schema == 1) {
                gray = (red + green + blue) / 3;
            } else if (schema == 2) {
                gray = (int) (0.3 * red + 0.59 * green + 0.11 * blue);
            }

            bm.setPixel(col, row, Color.argb(alpha, gray, gray, gray));
        }
    }
    return bm;
}

亮度調整與鏡像翻轉

亮度調整的巧思在於並非每個通道都加同樣的固定值,而是依該像素的灰度值按比例提升,這樣能避免暗部與亮部的對比被一味拉平:

public Bitmap brightness(Bitmap bitmap, double depth) {
    Bitmap bm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            int pixel = bitmap.getPixel(col, row);
            int red = Color.red(pixel);
            int green = Color.green(pixel);
            int blue = Color.blue(pixel);
            int alpha = Color.alpha(pixel);

            double gray = (0.3 * red + 0.59 * green + 0.11 * blue);

            red += (depth * gray);
            if (red > 255) red = 255;
            green += (depth * gray);
            if (green > 255) green = 255;
            blue += (depth * gray);
            if (blue > 255) blue = 255;

            bm.setPixel(col, row, Color.argb(alpha, red, green, blue));
        }
    }
    return bm;
}

鏡像翻轉則更單純,只需把目標 x 座標換算成 width - col - 1:

public Bitmap flip(Bitmap bitmap) {
    Bitmap bm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            int pixel = bitmap.getPixel(col, row);
            int red = Color.red(pixel);
            int green = Color.green(pixel);
            int blue = Color.blue(pixel);
            int alpha = Color.alpha(pixel);
            int ncol = width - col - 1;
            bm.setPixel(ncol, row, Color.argb(alpha, red, green, blue));
        }
    }
    return bm;
}

運行結果

布局與事件綁定

版面配置如下:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button android:id="@+id/button_gray_3"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="@string/process" />

        <Button android:id="@+id/button_inverse"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/button_gray_3"
            android:layout_toRightOf="@+id/button_gray_3"
            android:text="@string/inverse" />

        <Button android:id="@+id/button_gray_1"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/button_gray_3"
            android:layout_toRightOf="@+id/button_inverse"
            android:text="@string/nored" />

        <Button android:id="@+id/button_gray_2"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button_gray_3"
            android:text="@string/noblue" />

        <Button android:id="@+id/button_flip"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button_inverse"
            android:layout_toRightOf="@+id/button_gray_2"
            android:text="@string/flip" />

        <Button android:id="@+id/button_save"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button_gray_3"
            android:layout_toRightOf="@+id/button_flip"
            android:text="@string/save" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/image_content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_launcher" />
</LinearLayout>

MainActivity 的 onCreate 中,先用 Canvas 畫出一張佔位圖,再把各個按鈕的事件接上:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView iView = (ImageView) findViewById(R.id.image_content);
Bitmap b = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
Canvas c = new Canvas(b);
c.drawText("Load Image from here...", 50, 200, paint);
iView.setImageBitmap(b);

findViewById(R.id.button_save).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(getApplicationContext(),
                "Please load the image firstly...", Toast.LENGTH_SHORT).show();
        loadImage();
        ImageView iv = (ImageView) findViewById(R.id.image_content);
        iv.setImageBitmap(srcImage);
    }
});

findViewById(R.id.button_gray_3).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if (srcImage == null) {
            loadImage();
        }
        ImagePixelsProcessor processor = new ImagePixelsProcessor();
        Bitmap bm = processor.gray(srcImage, 2);   // 加權法
        ((ImageView) findViewById(R.id.image_content)).setImageBitmap(bm);
    }
});

findViewById(R.id.button_inverse).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if (srcImage == null) {
            loadImage();
        }
        ImagePixelsProcessor processor = new ImagePixelsProcessor();
        Bitmap bm = processor.brightness(srcImage, 0.3);
        ((ImageView) findViewById(R.id.image_content)).setImageBitmap(bm);
    }
});

findViewById(R.id.button_gray_1).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if (srcImage == null) {
            loadImage();
        }
        ImagePixelsProcessor processor = new ImagePixelsProcessor();
        Bitmap bm = processor.gray(srcImage, 0);   // 最大平均值法
        ((ImageView) findViewById(R.id.image_content)).setImageBitmap(bm);
    }
});

findViewById(R.id.button_gray_2).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if (srcImage == null) {
            loadImage();
        }
        ImagePixelsProcessor processor = new ImagePixelsProcessor();
        Bitmap bm = processor.gray(srcImage, 1);   // 等權平均法
        ((ImageView) findViewById(R.id.image_content)).setImageBitmap(bm);
    }
});

findViewById(R.id.button_flip).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if (srcImage == null) {
            loadImage();
        }
        ImagePixelsProcessor processor = new ImagePixelsProcessor();
        Bitmap bm = processor.flip(srcImage);
        ((ImageView) findViewById(R.id.image_content)).setImageBitmap(bm);
    }
});

效能上的坦白話

getPixel/setPixel 這套寫法概念清楚、適合教學與小圖處理,但正式專案中請慎用。原因在於它是逐像素的跨層呼叫,一張百萬像素的圖片就是上百萬次方法調用,在手机上跑往往需要數秒,且過程中會產生大量中間物件。若只是灰度化,用 ColorMatrix 搭配 Paint 的 ColorFilter 一行就能搞定,速度差異是數量級的;若要做更複雜的卷積運算,則應改用 getPixels/setPixels 批次搬運到陣列中計算,或直接下沉到 JNI。本文的價值在於把像素的組成與加工原理攤開來講清楚,實際落地時請記得換上更高效的工具。

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