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

Android 圖片處理:調用相機與系統裁剪功能

編輯:關於 Android 程式設計

使用者上傳頭像時,我們往往需要的不是原始大圖,而是一張符合特定比例與尺寸的裁切結果。好在 Android 內建了圖片裁剪 Activity,只要用 Intent 把參數傳過去,就能省下自己寫縮放框的大量功夫。

一、從圖庫選圖並裁剪

裁剪功能靠幾個 extra 參數驅動,其中 crop 是最關鍵的一個——少了它,最後不會出現裁剪頁面。

// 調用圖庫並進入裁剪流程
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra("crop", "true");        // 有這句才會出現裁剪頁面
intent.putExtra("aspectX", 5);          // 裁剪框寬高比
intent.putExtra("aspectY", 4);
intent.putExtra("output", Uri.fromFile(new File("/sdcard/1.jpg")));
intent.putExtra("outputFormat", "JPEG");  // 回傳格式

startActivityForResult(Intent.createChooser(intent, "選擇圖片"), PHOTO_CODE);

若還想限制輸出尺寸,可以再加上 outputX 與 outputY。要注意的是,這些 extra 屬於私有約定,不同廠商 ROM 的支援程度不一,某些機型會忽略部分參數,實作時最好保留一條「不裁剪、自行縮圖」的退路。

二、調用相機拍照

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
        Uri.fromFile(new File("/sdcard/1.jpg")));
startActivityForResult(intent, TAKE_PHOTO_CODE);

EXTRA_OUTPUT 指定輸出路徑後,縮圖 Benzene 會出現在 Intent 的 data 中,必須自己去檔案系統讀。

三、處理回傳結果

/**
 * 取得返回的相片
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != RESULT_OK) return;

    if (requestCode == TAKE_PHOTO_CODE) {
        // 拍照完成,接著進入裁剪
        File picture = new File(mPhotoCachePath[mSelectedPhoto]);
        startPhotoZoom(Uri.fromFile(picture));

    } else if (requestCode == PHOTO_CODE) {
        // 裁剪完成,讀取結果
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;   // 降採樣,避免 OOM
            Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/1.jpg", options);

            if (bitmap != null) {
                mCacheBitmap = bitmap;

                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(mPhotoCachePath[mSelectedPhoto]);
                    mCacheBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                } finally {
                    if (fos != null) fos.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

四、裁剪方法本體

/**
 * 裁剪圖片
 * @param uri 待裁剪圖片的 URI
 */
public void startPhotoZoom(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 5);
    intent.putExtra("aspectY", 4);
    intent.putExtra("output", Uri.fromFile(new File(mPhotoCachePath[mSelectedPhoto])));
    intent.putExtra("outputFormat", "JPEG");
    startActivityForResult(intent, PHOTO_CODE);
}

幾個實務提醒

第一,inSampleSize 是對抗 OutOfMemoryError 的第一道防線。手機相機動輒幾 MB 的影像,直接 decodeFile 很容易就把堆記憶體撐爆。

第二,存取 /sdcard 需要 WRITE_EXTERNAL_STORAGE 權限;Android 7.0 之後若要以 file:// 形式把 URI 傳給其他 App,必須改用 FileProvider,否則會拋 FileUriExposedException。

第三,本文示範的 com.android.camera.action.CROP 屬於非公開意圖,且 Android 11 起引入了套件可見性限制。新專案建議改用 UCrop 這類成熟的三方庫,或自行以 Bitmap + Canvas 實作裁剪,避免綁死在系統相機的私有行為上。

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