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

Android 拍照與相冊選圖,含圖片裁剪完整實作

編輯:關於 Android 程式設計

幾乎每個有註冊功能的 App 都需要「設定頭像」。這個看似簡單的功能,背後其實牽涉到相機啟動、相冊挑選、URI 取得、以及裁剪後的結果回傳。今天就把這套常用模組完整記錄下來,日後直接取用。

方案一:只取圖,不裁剪

這種做法最簡單,但風險是:不經縮放的原始照片尺寸動輒數 MB,直接塞進 ImageView 很容易觸發 OOM。正式專案若不打算做裁剪,至少也要在解碼時做 inSampleSize 降採樣。以下先示範流程。

整體思路:透過 Intent 呼叫系統資源,拍照走 ACTION_IMAGE_CAPTURE,相冊走 ACTION_GET_CONTENT,兩者都用 startActivityForResult() 等待結果。

版面配置 res/layout/activity_select_photo.xml(以對話框風格呈現的底部選單)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal">

    <LinearLayout
        android:id="@+id/dialog_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/select_photo_up_bg"
            android:orientation="vertical"
            android:paddingTop="5dp"
            android:paddingBottom="5dp">

            <Button
                android:id="@+id/btn_take_photo"
                android:layout_width="fill_parent"
                android:layout_height="35dp"
                android:background="@drawable/select_photo_bg"
                android:text="拍照選取" />

            <View
                android:layout_width="fill_parent"
                android:layout_height="0.5px"
                android:background="#828282" />

            <Button
                android:id="@+id/btn_pick_photo"
                android:layout_width="fill_parent"
                android:layout_height="35dp"
                android:background="@drawable/select_photo_bg"
                android:text="相冊選取" />

            <Button
                android:id="@+id/btn_cancel"
                android:layout_width="fill_parent"
                android:layout_height="35dp"
                android:layout_marginTop="20dip"
                android:background="@drawable/select_photo_bg"
                android:paddingTop="5dp"
                android:paddingBottom="5dp"
                android:text="取消"
                android:textColor="#ffff0000" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

SelectPhotoActivity.java

public class SelectPhotoActivity extends Activity implements OnClickListener {

    /** 使用相機拍照取得圖片 */
    public static final int SELECT_PIC_BY_TACK_PHOTO = 1;
    /** 使用相冊中的圖片 */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    /** 從 Intent 取回圖片路徑的 KEY */
    public static final String KEY_PHOTO_PATH = "photo_path";

    private Button btn_take_photo;
    private Button btn_pick_photo;
    private Button btn_cancel;

    /** 取得後的圖片路徑 */
    private String picPath;
    private Intent lastIntent;
    private Uri photoUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_photo);

        btn_take_photo = (Button) findViewById(R.id.btn_take_photo);
        btn_pick_photo = (Button) findViewById(R.id.btn_pick_photo);
        btn_cancel     = (Button) findViewById(R.id.btn_cancel);

        // 保留呼叫者的 Intent,稍後把結果塞回去
        lastIntent = getIntent();

        btn_take_photo.setOnClickListener(this);
        btn_pick_photo.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_take_photo:
                takePhoto();
                break;
            case R.id.btn_pick_photo:
                pickPhoto();
                break;
            case R.id.btn_cancel:
                this.finish();
                break;
            default:
                break;
        }
    }

    /** 拍照取得圖片 */
    private void takePhoto() {
        // 拍照前務必先確認外部儲存空間可用
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            /*
             * 這裡先透過 ContentResolver 取得一個目標 Uri 再交給相機,
             * 好處是拿到的是「原圖」而非品質被壓縮的縮圖。
             * 若不這麼做,onActivityResult 回傳的 bitmap 資料
             * 只是縮圖,放大後會模糊。
             */
            ContentValues values = new ContentValues();
            photoUri = this.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
        } else {
            Toast.makeText(getApplicationContext(), "內存卡不存在",
                           Toast.LENGTH_SHORT).show();
        }
    }

    /** 從相冊挑圖 */
    private void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();
        return super.onTouchEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            doPhoto(requestCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /** 取得圖片路徑並回傳給呼叫者 */
    private void doPhoto(int requestCode, Intent data) {
        if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
            // 部分機型在這裡會回傳 null,需另外保護
            if (data == null) {
                Toast.makeText(getApplicationContext(), "選擇圖片文件出錯",
                               Toast.LENGTH_SHORT).show();
                return;
            }
            photoUri = data.getData();
            if (photoUri == null) {
                Toast.makeText(getApplicationContext(), "選擇圖片文件出錯",
                               Toast.LENGTH_SHORT).show();
                return;
            }
        }

        String[] pojo = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            cursor.close();
        }

        if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG")
                             || picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
            lastIntent.putExtra(KEY_PHOTO_PATH, picPath);
            setResult(Activity.RESULT_OK, lastIntent);
            finish();
        } else {
            Toast.makeText(getApplicationContext(), "選擇圖片文件不正確",
                           Toast.LENGTH_SHORT).show();
        }
    }
}

對話框風格 res/values/styles.xml

<!-- 底部彈入彈出的動畫 -->
<style name="AnimBottom" parent="@android:style/Animation">
    <item name="android:windowEnterAnimation">@anim/push_bottom_in</item>
    <item name="android:windowExitAnimation">@anim/push_bottom_out</item>
</style>

<!-- 選取照片 Activity 的樣式:對話框風格 -->
<style name="DialogStyleBottom" parent="android:Theme.Dialog">
    <item name="android:windowAnimationStyle">@style/AnimBottom</item>
    <item name="android:windowFrame">@null</item>           <!-- 邊框 -->
    <item name="android:windowIsFloating">false</item>        <!-- 是否浮於 Activity 之上 -->
    <item name="android:windowIsTranslucent">true</item>      <!-- 半透明 -->
    <item name="android:windowNoTitle">true</item>            <!-- 無標題 -->
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:backgroundDimEnabled">true</item>     <!-- 背景模糊 -->
</style>

然後在清單檔的 Activity 節點上套用這個 style:

<activity
    android:name=".SelectPhotoActivity"
    android:theme="@style/DialogStyleBottom" />

權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

執行效果:

方案二:取圖後進行裁剪

實務上更常見的需求是「裁完再用」,例如設定頭像通常要固定為正方形。裁剪的做法是送出一個 com.android.camera.action.CROP 的 Intent,由系統挑選具備裁剪能力的 App 來處理。

public class CropPictureActivity extends Activity {

    private ImageView iv_photo;
    private String[] items = new String[] { "選擇本地圖片", "拍照" };

    /** 頭像名稱 */
    private static final String IMAGE_FILE_NAME = "image.jpg";

    private static final int IMAGE_REQUEST_CODE  = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crop);

        iv_photo = (ImageView) findViewById(R.id.iv_photo);
        iv_photo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }

    /** 顯示選擇對話框 */
    private void showDialog() {
        new AlertDialog.Builder(this)
            .setTitle("設置頭像")
            .setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            Intent intentFromGallery = new Intent();
                            intentFromGallery.setType("image/*");
                            intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
                            break;

                        case 1:
                            Intent intentFromCapture =
                                    new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            // 先確認儲存卡可用
                            String state = Environment.getExternalStorageState();
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                File path = Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_DCIM);
                                File file = new File(path, IMAGE_FILE_NAME);
                                intentFromCapture.putExtra(
                                        MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            }
                            startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);
                            break;
                    }
                }
            })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    startPhotoZoom(data.getData());
                    break;

                case CAMERA_REQUEST_CODE:
                    String state = Environment.getExternalStorageState();
                    if (state.equals(Environment.MEDIA_MOUNTED)) {
                        File path = Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_DCIM);
                        File tempFile = new File(path, IMAGE_FILE_NAME);
                        startPhotoZoom(Uri.fromFile(tempFile));
                    } else {
                        Toast.makeText(getApplicationContext(),
                                "未找到存儲卡,無法存儲照片!",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;

                case RESULT_REQUEST_CODE:
                    // 裁剪完成
                    if (data != null) {
                        getImageToView(data);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 呼叫系統裁剪功能
     * @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");

        // aspectX / aspectY 是「比例」
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX / outputY 是輸出的實際像素尺寸
        intent.putExtra("outputX", 340);
        intent.putExtra("outputY", 340);

        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /** 保存裁剪後的圖片並顯示 */
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(this.getResources(), photo);
            iv_photo.setImageDrawable(drawable);
        }
    }
}

效果圖:

幾個實務要點

裁剪的本質是「Intent 招標」。你只是送出一個裁剪請求,由裝置上所有具備裁剪能力的 App 來接。所以使用者可能看到一個選擇清單(例如系統相簿與「快圖瀏覽」同時出現),這是正常現象,並非 bug。

aspectX/aspectY 與 outputX/outputY 別搞混。前者是寬高比例,後者才是輸出的實際像素。想要 1:1 的頭像,兩組都要設定。

拍照存的路徑要自己指定。用 EXTRA_OUTPUT 搭配自己建立的 File Uri,才能拿到完整解析度的原圖;不指定的話,多數機型只會回傳一張縮圖。

Android 7.0 以上要注意 FileProvider。本文寫法(Uri.fromFile())在新版系統上會拋 FileUriExposedException。正確做法是在 res/xml/file_paths.xml 宣告路徑,再改用 FileProvider.getUriForFile() 取得 content:// 型別的 Uri,並記得加上 FLAG_GRANT_WRITE_URI_PERMISSION。

記得做 Runtime Permission。Android 6.0 起,讀寫外部儲存空間屬於危險權限,僅在 Manifest 宣告不夠,必須在執行期向使用者動態申請。

裁剪結果不宜過大。透過 return-data 直接回傳 Bitmap 有 1MB 左右的 TransactionTooLarge 風險,正式專案建議改走「裁剪後寫入指定 Uri,再用 ContentResolver.openInputStream() 讀回並降採樣」的做法。

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