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

Android 呼叫相機與相簿取圖並裁切成頭像的完整流程

編輯:關於 Android 程式設計

先講思路:Android 系統本身就內建了圖片裁切應用,因此我們只要把照片交給它,再把裁切好的結果取回自己的畫面顯示即可,不必自己實作裁剪 UI。

在許多 App 中都有頭像處理的需求:從相機或相簿取得照片、裁成指定比例、再設定或上傳。網路上的方案很多,但實際套用時常遇到相容性問題,特別是 Android 4.4 之後 Uri 的變化。本文把踩過的坑整理成一套可用流程。

整體設計

1. 取得圖片只有兩條路:相機拍攝、相簿選取。
2. 在 SD 卡建立資料夾,並準備兩個 Uri:一個存拍攝的原始大圖,一個存裁切後的結果。實測若共用同一個 Uri,當使用者拍照後不裁切,下次拿到的會是未處理的大圖,不僅覆蓋掉先前的成果,載入大圖時還容易 OOM。
3. 拍攝後呼叫系統裁切工具,輸出到 crop_file.jpg。
4. 相簿選取後同樣導向裁切,但 Uri 需要先轉換。
5. 最後從 crop_file.jpg 取回 Bitmap 顯示。

步驟一:呼叫系統相機

// 呼叫系統相機
Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 拍攝結果直接寫入 photo_file 的 Uri,不留在相簿
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imagePhotoUri);
startActivityForResult(intentCamera, PHOTO_REQUEST_CAREMA);

回呼時,把剛拍好的照片交給系統裁切工具:

case PHOTO_REQUEST_CAREMA:
    if (resultCode == RESULT_OK) {
        if (imagePhotoUri != null) {
            CropUtils.cropImageUri(this, imagePhotoUri, imageUri,
                    ibUserIcon.getWidth(), ibUserIcon.getHeight(), PHOTO_REQUEST_CUT);
        } else {
            ToastUtils.show(this, "沒有得到拍照圖片");
        }
    } else if (resultCode == RESULT_CANCELED) {
        ToastUtils.show(this, "取消拍照");
    } else {
        ToastUtils.show(this, "拍照失敗");
    }
    break;

裁切工具的呼叫方式:

// 呼叫系統裁切功能,並把結果存到 desUri
public static void cropImageUri(Activity activity, Uri orgUri, Uri desUri,
                                int width, int height, int requestCode) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(orgUri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", width);
    intent.putExtra("outputY", height);
    intent.putExtra("scale", true);
    // 將裁切結果存到目標 Uri
    intent.putExtra(MediaStore.EXTRA_OUTPUT, desUri);
    intent.putExtra("return-data", false);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true);
    activity.startActivityForResult(intent, requestCode);
}

步驟二:取回裁切後的圖片

因為裁切時已經過一次縮放,直接解碼即可,不必再擔心記憶體:

case PHOTO_REQUEST_CUT:
    if (resultCode == RESULT_OK) {
        Bitmap bitmap = decodeUriAsBitmap(this, imageCropUri);
    } else if (resultCode == RESULT_CANCELED) {
        ToastUtils.show(this, "取消剪切圖片");
    } else {
        ToastUtils.show(this, "剪切失敗");
    }
    break;
// 從 Uri 取得 Bitmap
private static Bitmap decodeUriAsBitmap(Context context, Uri uri) {
    Bitmap bitmap;
    try {
        bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }
    return bitmap;
}

若需要圓形頭像,可以在這裡多做一次遮罩處理:

// 取得圓形圖片
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    if (bitmap == null) {
        return null;
    }
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);

    // 取正方形,並置中
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int w;
    int deltaX = 0;
    int deltaY = 0;
    if (width <= height) {
        w = width;
        deltaY = height - w;
    } else {
        w = height;
        deltaX = width - w;
    }
    final Rect rect = new Rect(deltaX, deltaY, w, w);
    final RectF rectF = new RectF(rect);
    canvas.drawARGB(0, 0, 0, 0);

    // 以對角線一半作為圓角半徑,畫出圓形遮罩
    int radius = (int) (Math.sqrt(w * w * 2.0d) / 2);
    canvas.drawRoundRect(rectF, radius, radius, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
}

步驟三:相簿選取(Android 4.4 的難關)

Android 4.4 以下,從相簿取得的 Uri 可以直接交給裁切工具,一切美好。但 4.4 以後,Google 改用 Intent.ACTION_GET_CONTENT,回傳的是 content://com.android.externalstorage.documents/... 這類新型 Documents Uri,直接丟給裁切 Intent 會直接崩潰。解法是把新型 Uri 還原成標準的絕對路徑,再重新包裝成 file://...。

呼叫相簿:

// 呼叫系統相簿
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PHOTO_REQUEST_GALLERY);

回呼時重新包裝 Uri(裁切呼叫同上,不重複貼出):

case PHOTO_REQUEST_GALLERY:
    if (resultCode == RESULT_OK) {
        // 先把 Uri 還原成真實路徑,再進行裁切
        Uri newUri = Uri.parse("file:///" + CropUtils.getPath(this, data.getData()));
        if (newUri != null) {
            CropUtils.cropImageUri(this, newUri, imageUri,
                    ibUserIcon.getWidth(), ibUserIcon.getHeight(), PHOTO_REQUEST_CUT);
        } else {
            ToastUtils.show(this, "沒有得到相冊圖片");
        }
    } else if (resultCode == RESULT_CANCELED) {
        ToastUtils.show(this, "從相冊選取取消");
    } else {
        ToastUtils.show(this, "從相冊選取失敗");
    }
    break;

Uri 轉路徑的核心工具方法:

@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{ split[1] };
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore 與一般情況
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

/** 取得 _data 欄位,通常是檔案路徑 */
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null) cursor.close();
    }
    return null;
}

private static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

private static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

private static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

後續的裁切呼叫與拍照流程完全一致。這套做法在 Nexus 5 與小米、三星等機型上都實測通過。

補充一個更簡潔的思路:Android 4.4 以上也可以搭配 UCrop 這類第三方裁切庫,或使用 com.android.camera.action.CROP 失敗時退回 Intent.ACTION_PICK 並自行裁切,能少掉不少版本判斷的麻煩。此外,若 targetSdk 已達 Android 10 以上,直接存取 _data 路徑會受強制/storage 權限規範限制,建議改用 ContentResolver 開啟 openInputStream() 搭配 BitmapFactory.decodeStream(),並把裁切結果寫入 FileProvider 提供的 Uri。

功能雖已實現,程式碼仍有優化空間,有興趣的可以自行調整。

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