編輯:關於 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));
使用 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);
最常見的圖像處理莫過於去色。三種常用算法的差別在於權重:
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。本文的價值在於把像素的組成與加工原理攤開來講清楚,實際落地時請記得換上更高效的工具。
Android 使用 Gson 解析 JSON 教學
Gson 是 Google 提供的 Java 函式庫,主要用來在 Java 物件與 JSON 資料之間進行轉換。透過 Gson,開發者可以很輕鬆地將物件轉成 JSON,也
用自定義命名空間,做一個會變色的橫向柱狀圖
先上圖: 效果很簡單:一個 ListView,item 是自定義 View,具備兩個特點——可以傳入長度動態改變柱子長短;並依長度改變色值,越長越偏紅,越短越偏黃。 用
Android 效能分析利器:Systrace 介紹與使用
一、簡介 Systrace 是 Android 4.1 開始引入的一套管線式效能分析工具。它建立在 Linux 核心的 ftrace 機制之上(ftrace 主要用於追蹤
Java/Android synchronized 的四種用法與鎖的粒度
synchronized 是 Java 最基本的同步手段。關鍵在於搞清楚「鎖的對象是誰」,因為鎖對象決定了互斥的範圍。實務上共有四種寫法。 一、修飾方法 放在修飾符之後