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

Android 相機與相冊調用、圖片處理與檔案管理實戰

編輯:關於 Android 程式設計

拍照、選圖、調色、存檔、刪除——這幾件事幾乎每個需要處理圖片的 App 都會遇到。這篇用一個完整的圖片處理範例把它們串起來,並說明其中的關鍵細節。

一、功能盤點

範例畫面包含一個 ImageView 用於預覽,四個 SeekBar 分別控制透明度與 RGB 三通道,再加上拍照、相冊、保存、初始化、刪除、檢視六個按鈕。

二、佈局結構

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_change"
        android:layout_width="fill_parent"
        android:layout_height="220dp"
        android:maxHeight="1000dp"
        android:maxWidth="1000dp"
        android:scaleType="fitXY"
        android:src="@drawable/origin" />

    <SeekBar android:id="@+id/sb_alpha" ... />
    <SeekBar android:id="@+id/sb_red" ... />
    <SeekBar android:id="@+id/sb_green" ... />
    <SeekBar android:id="@+id/sb_blue" ... />

    <TextView
        android:id="@+id/tv_display"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#333333"
        android:textSize="16sp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:orientation="horizontal">
        <!-- 拍照 / 相冊 / 保存 / 初始化 / 刪除 / 檢視 -->
    </LinearLayout>
</LinearLayout>

三、初始化與目錄準備

先建立存放圖片的目錄,並把原始圖從資源中解碼出來:

// 在外部儲存空間下建立 mFilter 目錄
Path = Environment.getExternalStorageDirectory() + "/mFilter";
File dir = new File(Path);
if (!dir.exists()) {
    dir.mkdir();
}

// 從資源載入原圖
photoorigin = BitmapFactory.decodeResource(getResources(), R.drawable.origin);

RGB 三個進度條的初始值都設為 50,因為後續換算時會以 50 為中點做偏移——50 代表「不調整」。

四、用 ColorMatrix 做調色

調色是這個範例的核心。SeekBar 的進度先換算成矩陣係數,再灌進 ColorMatrix:

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    switch (seekBar.getId()) {
        case R.id.sb_alpha:
            a = progress / 100.0f;
            break;
        case R.id.sb_red:
            r = (progress - 50) / 5.0f;
            break;
        case R.id.sb_green:
            g = (progress - 50) / 5.0f;
            break;
        case R.id.sb_blue:
            b = (progress - 50) / 5.0f;
            break;
    }
    setArgb(1 - a, r + 1, g + 1, b + 1);
}

4x5 的顏色矩陣中,每個色彩通道佔一行,最後一列的第 20 個位置則是 alpha 的乘數:

ColorMatrix matrix = new ColorMatrix(new float[]{
        red,   0,     0,     0,     0,
        0,     green, 0,     0,     0,
        0,     0,     blue,  0,     0,
        0,     0,     0,     alpha, 0
});
iv_change.getDrawable().setColorFilter(new ColorMatrixColorFilter(matrix));

這裡有個實務上必須知道的限制:setColorFilter 只改變 Drawable 的顯示效果,並不會改動背後的 Bitmap 像素。所以後續要存檔時,不能靠 Drawable 去取圖。

五、拍照與相冊

相冊用 ACTION_PICK 搭配圖片 MIME 過濾:

private void takepicture() {
    Intent intent = new Intent(Intent.ACTION_PICK, null);
    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    startActivityForResult(intent, 0);
}

拍照則用 ACTION_IMAGE_CAPTURE,並透過 EXTRA_OUTPUT 指定輸出路徑:

private void takephoto() {
    mCurrentPhotoFile = new File(Path, "temp.jpg");
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
    startActivityForResult(intent, 1);
}

指定 EXTRA_OUTPUT 是關鍵:不指定的話,系統會把縮圖當作 Bitmap 直接塞進 Intent 的 extras 中,這個做法在解析度高的裝置上很容易引發 TransactionTooLargeException 或 OutOfMemoryError。

六、接收結果

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case 0:  // 相冊
            if (data != null) {
                Uri uri = data.getData();
                ContentResolver cr = getContentResolver();
                try {
                    if (photo != null && !photo.isRecycled()) {
                        photo.recycle();
                        System.gc();
                    }
                    photo = BitmapFactory.decodeStream(cr.openInputStream(uri));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                iv_change.setImageBitmap(photo);
            }
            break;

        case 1:  // 拍照
            if (resultCode == RESULT_OK) {
                ContentResolver cr = getContentResolver();
                Uri fileUri = Uri.fromFile(mCurrentPhotoFile);
                // 通知媒體掃描器收錄這個新檔案,否則相冊中看不到
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
                try {
                    if (photo != null && !photo.isRecycled()) {
                        photo.recycle();
                        System.gc();
                    }
                    photo = BitmapFactory.decodeStream(cr.openInputStream(fileUri));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                iv_change.setImageBitmap(photo);
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

那行 ACTION_MEDIA_SCANNER_SCAN_FILE 廣播常被遺漏。少了它,照片確實存在於檔案系統,但媒體庫沒有索引,使用者在相冊裡就是找不到。

七、存檔

要保存「使用者看到的畫面」,正確做法是透過 View 的 DrawingCache:

private void saveImageView() {
    final String path = Path + "/" + getNowDateTime("yyyyMMddHHmmss") + ".jpg";

    iv_change.setDrawingCacheEnabled(true);
    Bitmap result = iv_change.getDrawingCache();
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
        result.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        iv_change.setDrawingCacheEnabled(false);  // 用完立刻關閉,避免快取常駐記憶體
    }
}

需要提醒的是,DrawingCache 會在記憶體中額外配置一張與 View 等大的 Bitmap,用完必須關閉;同時在 Android 6.0 以上,寫入外部儲存需要 READ/WRITE_EXTERNAL_STORAGE 的執行期授權,忘了申請會直接失敗。

八、清除與檢視

private void delete() {
    File dir = new File(Path);
    File[] children = dir.listFiles();
    if (children != null) {
        for (File file : children) {
            file.delete();
        }
    }
}

刪除前用 AlertDialog 二次確認,刪完再列一次目錄判斷是否真的清空——這種「做後驗證」的習慣,比直接彈出成功提示可靠得多。

九、進階:裁剪

需要固定尺寸裁切時,可以呼叫系統相機的 CROP 動作:

private void startPhotoZoom(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);    // 寬高比例
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 320);  // 輸出圖片寬高
    intent.putExtra("outputY", 320);
    intent.putExtra("return-data", true);
    startActivityForResult(intent, REQUEST_CODE_HEAD);
}
private Bitmap saveImageView(Intent data) throws IOException {
    Bundle extras = data.getExtras();
    if (extras != null) {
        Bitmap photo = extras.getParcelable("data");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
        photo.compress(Bitmap.CompressFormat.JPEG, 60, bos);
        bos.flush();
        bos.close();
        return photo;
    }
    return null;
}

這個做法依賴各廠商相機的實作,相容性並不 guarantee。若要穩定支援,建議改用 UCrop 這類專門的裁剪庫,或自行以 Bitmap.createBitmap + Canvas 繪製裁切。

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