編輯:Android 開發實例
在 Android 上用 Java 實作彩圖轉灰度圖,思路與 J2ME 上類似;但一旦遇到需要頻繁轉換或影像尺寸偏大的情況,就非得請 NDK 出馬才能把速度拉回來。本文分別用 Java 與 NDK 兩種方式實作同一件事,並直接比較兩者的耗時。
以下以 NDK r4 為例,日後新版本的流程可能略有差異。
1、下載支援 C++ 的 android-ndk-r4-crystax,支援 C++ 之後可玩性高很多……
2、下載 cygwin,選擇ftp://mirrors.kernel.org這個鏡像,在搜尋框中分別搜尋 gcc 與 make(必須是 Devel Install 欄的項目),把編譯工具裝起來;
3、在 Cygwin 的安裝目錄下找到 home/username,開啟其中的 .bash_profile,在檔案最後補上:
NDK=/cygdrive/d/android-ndk-r4-windows/android-ndk-r4
export NDK
PS:這裡假設 NDK 裝在 d:\android-ndk-r4-windows\android-ndk-r4。
4、啟動 cygwin,用 cd 指令進入 NDK\samples\範例目錄\,執行 $NDK/ndk-build 來編譯該目錄下的 Android.mk
以下是個人習慣……
5、安裝 Eclipse 的 CDT,官方下載 cdt 套件後解壓縮,把 plugins 與 features 複製覆蓋到 eclipse 資料夾即可
6、到「系統內容 → 環境變數 → Path」加入 "D:\cygwin\bin"(假設 cygwin 裝在 D 槽),重新開機後就能在 Eclipse 裡建立以 cygwin 為基礎的 C/C++ 專案。先用這一步確認 NDK 程式編譯得過,再回到第 4 步產生 SO 檔。
接著看程式執行的結果:
從轉換灰度圖的耗時來看,NDK 的確比 Java 快上不少。
main.xml 如下:
<?xml version="1.0" encoding="utf-8" ?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/btnJAVA" android:text="使用 JAVA 轉換灰度圖" /> <Button android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/btnNDK" android:text="使用 NDK 轉換灰度圖" /> <ImageView android:id="@+id/ImageView01" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
主程式 testToGray.java:
package com.testToGray;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class testToGray extends Activity {
Button btnJAVA, btnNDK;
ImageView imgView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("使用 NDK 轉換灰度圖---hellogv");
btnJAVA = (Button) this.findViewById(R.id.btnJAVA);
btnJAVA.setOnClickListener(new ClickEvent());
btnNDK = (Button) this.findViewById(R.id.btnNDK);
btnNDK.setOnClickListener(new ClickEvent());
imgView = (ImageView) this.findViewById(R.id.ImageView01);
}
class ClickEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
if (v == btnJAVA) {
long current = System.currentTimeMillis();
Bitmap img = ConvertGrayImg(R.drawable.cat);
long performance = System.currentTimeMillis() - current;
imgView.setImageBitmap(img); // 顯示灰度圖
testToGray.this.setTitle("w:" + String.valueOf(img.getWidth()) + ",h:" + String.valueOf(img.getHeight())
+ " JAVA 耗時 " + String.valueOf(performance) + " 毫秒");
} else if (v == btnNDK) {
long current = System.currentTimeMillis();
// 先開啟影像並取出像素
Bitmap img1 = ((BitmapDrawable) getResources().getDrawable(R.drawable.cat)).getBitmap();
int w = img1.getWidth(), h = img1.getHeight();
int[] pix = new int[w * h];
img1.getPixels(pix, 0, w, 0, 0, w, h);
// 透過 ImgToGray.so 把彩色像素轉為灰度像素
int[] resultInt = LibFuns.ImgToGray(pix, w, h);
Bitmap resultImg = Bitmap.createBitmap(w, h, Config.RGB_565);
resultImg.setPixels(resultInt, 0, w, 0, 0, w, h);
long performance = System.currentTimeMillis() - current;
imgView.setImageBitmap(resultImg);
testToGray.this.setTitle("w:" + String.valueOf(img1.getWidth()) + ",h:" + String.valueOf(img1.getHeight())
+ " NDK 耗時 " + String.valueOf(performance) + " 毫秒");
}
}
}
/**
* 把資源圖片轉為灰度圖(純 Java 版本)
* @param resID 資源 ID
* @return 轉換後的 Bitmap
*/
public Bitmap ConvertGrayImg(int resID) {
Bitmap img1 = ((BitmapDrawable) getResources().getDrawable(resID)).getBitmap();
int w = img1.getWidth(), h = img1.getHeight();
int[] pix = new int[w * h];
img1.getPixels(pix, 0, w, 0, 0, w, h);
int alpha = 0xFF << 24;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
// 取得像素的顏色
int color = pix[w * i + j];
int red = ((color & 0x00FF0000) >> 16);
int green = ((color & 0x0000FF00) >> 8);
int blue = color & 0x000000FF;
color = (red + green + blue) / 3;
color = alpha | (color << 16) | (color << 8) | color;
pix[w * i + j] = color;
}
}
Bitmap result = Bitmap.createBitmap(w, h, Config.RGB_565);
result.setPixels(pix, 0, w, 0, 0, w, h);
return result;
}
}
封裝 NDK 函式的 Java 類別 LibFuns.java:
package com.testToGray;
public class LibFuns {
static {
System.loadLibrary("ImgToGray");
}
/**
* @param buf 像素陣列
* @param w 影像寬度
* @param h 影像高度
*/
public static native int[] ImgToGray(int[] buf, int w, int h);
}
彩圖轉灰度圖的 ImgToGray.cpp:
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
extern "C" {
JNIEXPORT jintArray JNICALL Java_com_testToGray_LibFuns_ImgToGray(
JNIEnv* env, jobject obj, jintArray buf, int w, int h);
};
JNIEXPORT jintArray JNICALL Java_com_testToGray_LibFuns_ImgToGray(
JNIEnv* env, jobject obj, jintArray buf, int w, int h) {
jint *cbuf;
cbuf = env->GetIntArrayElements(buf, false);
if (cbuf == NULL) {
return 0; /* exception occurred */
}
int alpha = 0xFF << 24;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
// 取得像素的顏色
int color = cbuf[w * i + j];
int red = ((color & 0x00FF0000) >> 16);
int green = ((color & 0x0000FF00) >> 8);
int blue = color & 0x000000FF;
color = (red + green + blue) / 3;
color = alpha | (color << 16) | (color << 8) | color;
cbuf[w * i + j] = color;
}
}
int size = w * h;
jintArray result = env->NewIntArray(size);
env->SetIntArrayRegion(result, 0, size, cbuf);
env->ReleaseIntArrayElements(buf, cbuf, 0);
return result;
}
Android.mk:
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := ImgToGray LOCAL_SRC_FILES := ImgToGray.cpp include $(BUILD_SHARED_LIBRARY)
最後補一個觀念:這裡之所以能明顯變快,關鍵不在「C++ 比 Java 快」這麼籠統,而在於整段像素迴圈被搬進原生層一次跑完,省下了每個像素跨過 JNI 邊界的成本。反過來說,如果只是想呼叫幾次小函式,跨語言的呼叫與資料轉換開銷反而可能讓 NDK 版本更慢——NDK 適合的是「計算密集、資料量大、可以整批處理」的場景。
Android 懸浮視窗實作:用 WindowManager 打造可拖曳的浮動層
懸浮視窗是那種「用過一次就忘不掉」的互動模式:不佔滿畫面、不屬於任何 Activity,卻能一直浮在上層,還能拖著跑。聊天工具的懸浮球、音樂播放器的小視窗、計時器的小鬧鐘
Android PreferenceActivity 詳解:用系統設定頁的架構做自己的設定介面
很多書對 PreferenceActivity 幾乎一筆帶過,但它在真實專案裡非常好用。本文把它的資料保存機制、建立方式、可用元素與事件回呼一次講完。 先看長相 左圖
Android 網路請求與圖片快取框架 enif 深入解析
enif 是一套針對早期 Android 應用設計的輕量框架,主要解決兩個常見問題:網路請求的統一管理,以及列表圖片載入時的快取與記憶體控制。它將底層連線、非同步任務、監
Android 載入 Spinner 進度條實作教學
在 Android 中,可以透過進度條來向使用者顯示某項任務的執行進展。進度條主要分為兩種形態:進度列與旋轉式載入指示器(Spinner)。本章將聚焦於後者。 Spinn