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

呼叫系統相機拍照與裁剪圖片:startActivityForResult 的標準用法

編輯:關於 Android 程式設計

大多數情況下不需要自己寫相機,直接叫起系統的拍照與裁剪功能就好。重點在於 startActivityForResult() 的搭配,以及幾個容易被忽略的系統 action 與 extra 參數。

Activity 實作

package com.photosizing;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class TestActivity extends Activity {

    public static final int NONE = 0;
    public static final int PHOTOHRAPH = 1;   // 拍照
    public static final int PHOTOZOOM = 2;    // 裁剪
    public static final int PHOTORESOULT = 3; // 結果
    public static final String IMAGE_UNSPECIFIED = "image/*";

    ImageView imageView;
    Button button0;
    Button button1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageView = (ImageView) findViewById(R.id.imageID);
        button0 = (Button) findViewById(R.id.btn_01);
        button1 = (Button) findViewById(R.id.btn_02);

        // 從相簿挑圖
        button0.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        IMAGE_UNSPECIFIED);
                startActivityForResult(intent, PHOTOZOOM);
            }
        });

        // 直接拍照
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
                startActivityForResult(intent, PHOTOHRAPH);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_CANCELED) return;
        if (data == null && requestCode != PHOTOHRAPH) return;

        switch (requestCode) {
            case PHOTOHRAPH:
                // 拍照後的檔案在固定路徑
                File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
                startPhotoZoom(Uri.fromFile(picture));
                break;

            case PHOTOZOOM:
                // 從相簿回傳的 Uri
                startPhotoZoom(data.getData());
                break;

            case PHOTORESOULT:
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);
                    imageView.setImageBitmap(photo);
                }
                break;
        }
    }

    /**
     * 呼叫系統裁剪
     * @param uri 要裁剪的圖片
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");

        // aspectX / aspectY 為裁剪框的寬高「比例」
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

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

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

布局檔

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ImageView
        android:id="@+id/imageID"
        android:adjustViewBounds="true"
        android:maxWidth="50dip"
        android:maxHeight="50dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_01"
        android:layout_height="50dip"
        android:layout_width="150dip"
        android:text="相簿" />

    <Button
        android:id="@+id/btn_02"
        android:layout_height="50dip"
        android:layout_width="150dip"
        android:text="拍照" />
</LinearLayout>

參數釐清

  • aspectX / aspectY 是裁剪框的比例,不是像素值。寫 1:1 就是正方形。
  • outputX / outputY 是輸出的實際像素尺寸。兩者經常被搞混。
  • return-data = true 表示把結果以 Bitmap 直接塞回 Intent 的 extras。這有個陷阱:多大的圖會造成 TransactionTooLargeException,因此 outputX/outputY 不宜設太大(實務上 200~500 px 較安全)。若要處理大圖,應改為 return-data = false 並用 EXTRA_OUTPUT 指定輸出檔案路徑,再自行讀取。

現代版本的注意事項

這份程式碼用了幾個已被淘汰的寫法,移植時務必調整:

  • com.android.camera.action.CROP 是非官方的隱式 action,各家 ROM 的實作不一,部分機型根本沒有對應的 Activity,會直接 ActivityNotFoundException。建議自行用 Bitmap + Canvas 裁剪,或改用 UCrop 這類成熟函式庫。
  • 寫入 Environment.getExternalStorageDirectory() 根目錄需要 WRITE_EXTERNAL_STORAGE 權限,且 Android 10 之後因 Scoped Storage 已不被允許,請改用 getExternalFilesDir() 或 FileProvider。
  • Android 7.0 起不得將 file:// URI 傳給其他 App,必須用 FileProvider 產生 content:// URI 並加上 FLAG_GRANT_READ_URI_PERMISSION。
  • 拍照前記得檢查 resolveActivity() 是否有 App 能處理這個 Intent,避免直接崩潰。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved