編輯:關於 Android 程式設計
上一篇我們講了 Android 拍照、截圖、保存並顯示到 ImageView,這一篇接著往下談圖像處理。主題是:從相冊打開一張圖片,用 Matrix 對它做縮放、旋轉、移動、對比度、亮度與飽和度的調整。
第一步是搭好介面。activity_main.xml 的結構如下:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="選擇圖片" />
<TextView android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
android:text="原圖顯示" />
<ImageView android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<TextView android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
android:text="變化後的圖片" />
<ImageView android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true" >
<Button android:id="@+id/button2" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:text="縮小" />
<Button android:id="@+id/button3" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:text="放大" />
<Button android:id="@+id/button4" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:text="旋轉" />
<Button android:id="@+id/button5" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:text="飽和" />
<Button android:id="@+id/button6" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:text="對比" />
</LinearLayout>
</RelativeLayout>
接著在 MainActivity.java 中宣告成員變數,並為「選擇圖片」按鈕掛上監聽器:
private Button selectBn;
private ImageView imageShow;
private ImageView imageCreate;
private TextView textview1;
private TextView textview2;
private Bitmap bmp; // 原始圖片
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectBn = (Button) findViewById(R.id.button1);
imageShow = (ImageView) findViewById(R.id.imageView1);
imageCreate = (ImageView) findViewById(R.id.imageView2);
textview1 = (TextView) findViewById(R.id.textView1);
textview2 = (TextView) findViewById(R.id.textView2);
// 選擇圖片
selectBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});
}
// 回傳結果:顯示原圖,並建立第二張待處理的圖
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
ShowPhotoByImageView(data); // 顯示照片
CreatePhotoByImageView(); // 建立圖片
}
}
真正負責顯示的兩個自訂方法:
// 把相冊選的照片顯示到 imageView1
public void ShowPhotoByImageView(Intent data) {
Uri imageFileUri = data.getData();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; // 螢幕水平解析度
int height = dm.heightPixels; // 螢幕垂直解析度
try {
// 先只讀取圖片尺寸,不載入圖片本身
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
bmp = BitmapFactory.decodeStream(
getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio * 2;
} else {
bmpFactoryOptions.inSampleSize = widthRatio * 2;
}
}
// 真正解碼
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeStream(
getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
imageShow.setImageBitmap(bmp);
textview1.setVisibility(View.VISIBLE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 建立第二張圖片並顯示
public void CreatePhotoByImageView() {
try {
Bitmap createBmp = Bitmap.createBitmap(
bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(createBmp); // 畫布,傳入位圖用於繪製
Paint paint = new Paint(); // 畫刷,可改顏色、對比度等屬性
canvas.drawBitmap(bmp, 0, 0, paint); // 注意:這裡若誤寫成 createBmp 會沒有圖
imageCreate.setImageBitmap(createBmp);
textview2.setVisibility(View.VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
執行後畫面如下。這張測試圖叫萊娜圖(Lenna),是圖像處理領域經常被拿來當範例的一張經典素材。
先替五顆按鈕掛上點擊事件:
// 縮小
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
public void onClick(View v) { SmallPicture(); }
});
// 放大
findViewById(R.id.button3).setOnClickListener(new OnClickListener() {
public void onClick(View v) { BigPicture(); }
});
// 旋轉
findViewById(R.id.button4).setOnClickListener(new OnClickListener() {
public void onClick(View v) { TurnPicture(); }
});
// 飽和度
findViewById(R.id.button5).setOnClickListener(new OnClickListener() {
public void onClick(View v) { SaturationPicture(); }
});
// 對比度
findViewById(R.id.button6).setOnClickListener(new OnClickListener() {
public void onClick(View v) { ContrastPicture(); }
});
相關的狀態變數:
private float smallbig = 1.0f; // 縮放比例 private int turnRotate = 0; // 旋轉度數 private float saturation = 0f; // 飽和度
五個處理函式:
// 縮小圖片
private void SmallPicture() {
Matrix matrix = new Matrix();
if (smallbig > 0.5f) smallbig = smallbig - 0.1f; // 縮放區間 0.5 ~ 1.0
else smallbig = 0.5f;
// x、y 座標同時縮放,以圖片中心為基準
matrix.setScale(smallbig, smallbig, bmp.getWidth() / 2, bmp.getHeight() / 2);
Bitmap createBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(createBmp);
Paint paint = new Paint();
canvas.drawBitmap(bmp, matrix, paint);
imageCreate.setBackgroundColor(Color.RED);
imageCreate.setImageBitmap(createBmp);
textview2.setVisibility(View.VISIBLE);
}
// 放大圖片
private void BigPicture() {
Matrix matrix = new Matrix();
if (smallbig < 1.5f) smallbig = smallbig + 0.1f;
else smallbig = 1.5f;
matrix.setScale(smallbig, smallbig, bmp.getWidth() / 2, bmp.getHeight() / 2);
Bitmap createBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(createBmp);
Paint paint = new Paint();
canvas.drawBitmap(bmp, matrix, paint);
imageCreate.setBackgroundColor(Color.RED);
imageCreate.setImageBitmap(createBmp);
textview2.setVisibility(View.VISIBLE);
}
// 旋轉圖片
private void TurnPicture() {
Matrix matrix = new Matrix();
turnRotate = turnRotate + 15;
// 正數為順時針,負數為逆時針,這裡繞圖片中心旋轉
matrix.setRotate(turnRotate, bmp.getWidth() / 2, bmp.getHeight() / 2);
Bitmap createBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(createBmp);
Paint paint = new Paint();
canvas.drawBitmap(bmp, matrix, paint);
imageCreate.setBackgroundColor(Color.RED);
imageCreate.setImageBitmap(createBmp);
textview2.setVisibility(View.VISIBLE);
}
// 改變飽和度
private void SaturationPicture() {
// 0 為灰階,介於 0~1 飽和度遞減,大於 1 遞增
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(saturation);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
Matrix matrix = new Matrix();
Bitmap createBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(createBmp);
canvas.drawBitmap(bmp, matrix, paint);
imageCreate.setImageBitmap(createBmp);
textview2.setVisibility(View.VISIBLE);
saturation = saturation + 0.1f;
if (saturation >= 1.5f) saturation = 0f;
}
// 改變對比度(同時帶入亮度)
private void ContrastPicture() {
ColorMatrix cm = new ColorMatrix();
float brightness = -25; // 亮度
float contrast = 2; // 對比度
cm.set(new float[] {
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, contrast, 0
});
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
Matrix matrix = new Matrix();
Bitmap createBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(createBmp);
canvas.drawBitmap(bmp, matrix, paint);
imageCreate.setImageBitmap(createBmp);
textview2.setVisibility(View.VISIBLE);
}
運行結果如下:
要坦白說明的是:這個範例只示範處理流程,並沒有把各種細節都照顧到。例如部分圖片可能超出螢幕、還沒載入圖片就點擊處理鈕會報錯、橫豎屏切換後圖片不顯示、最下方的按鈕可能被遮擋,另外放大時畫布尺寸並沒有跟著變(這是刻意保留的,只呈現一張「處理後」的圖更好對照)。至於更順手的縮放與拖曳,需要搭配觸控事件處理,留待下一篇再談。
在 Android 中,可以透過 Matrix 與 ColorMatrix 兩條路徑來處理圖像。
1. Matrix
負責的是圖像的空間變換,包含旋轉、剪裁、縮放與位移。Matrix 類裡的每個數字,都會被套用到圖像上每一個點的三個座標 x、y、z 之一。
例如下面這段程式用 setValues 設定了一組值,(1,0,0) 代表 x = 1x + 0y + 0z,同理 y = 0x + 1y + 0z、z = 0x + 0y + 1z,這一組值不做任何變換。如果把第一行改成 (.5f, 0, 0),那麼圖像在 x 軸方向上就會被壓縮 50%。位移則對應 setTranslate() 方法。
Matrix matrix = new Matrix();
matrix.setValues(new float[] {
1, 0, 0,
0, 1, 0,
0, 0, 1
});
2. ColorMatrix
在 Canvas 上繪製時,除了 Matrix,也可以改用 ColorMatrix 去改變 Paint 畫刷的表現。處理像素時,每個像素由 RGBA 四個分量組成(Red、Green、Blue、Alpha),ColorMatrix 正是作用在這四個通道上的色彩矩陣運算,因此飽和度、對比度、亮度這類調整都靠它完成。
以上就是使用 Matrix 處理圖片的基礎入門。若有不足或疏漏之處,還請多包容指教。參考資料:《Android 多媒體開發高級編程》(Shawn Van Every 著)。
1080P手機變卡又耗電?手動降低解析度與密度
1080P手機若跑遊戲或模擬器吃緊,可手動降低解析度。Root後編輯build.prop,把ro.sf.lcd_density從480改為320,再用終端模擬器調整顯示尺
Android 自定義 View(四):一步步還原 QQ 健康介面
自定義 View 是 Android 的必備技能。這次我們拿 QQ 健康(運動)頁當作練習題,它涵蓋了自訂屬性、onMeasure、Path 繪製、DashPathEff
Android 自定義 View 實作:彎曲滑桿指示器完整解析
Android 自定義 View:彎曲滑桿指示器實作 本文說明如何實作一個弧形滑桿指示器。它包含圓弧軌道、可拖動小球、文字標籤,以及點擊文字後自動移動小球的能力。 整體
Android 開發常用工具方法大盤點
這篇文章彙集了 Android 日常開發中反覆用到的實用工具方法與技巧,涵蓋記憶體讀取、單位換算、屏幕適配、異常捕獲等常見需求,方便隨時查閱。 AIDL 是什麼以及如何使