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

Android 拍照與相冊選圖並裁剪:完整流程與踩坑筆記

編輯:關於 Android 程式設計

「更換頭像」大概是每個 App 都有的功能:讓使用者拍照或從相冊挑一張,裁切成指定比例後顯示在 ImageView 上(實務上通常還要上傳到伺服器)。這個流程看似簡單,卻牽涉到 Uri 取得、相機 Intent 與裁剪 Intent 的串接,中間任何一步處理不當都會拿到模糊縮圖或直接 crash。

以下程式碼參考網上資料並結合專案實況整理,在多款機型上測試過,暫時沒有發現嚴重問題。程式碼已附上註解:

 public class UploadPicActivity extends Activity implements View.OnClickListener {

     private Button take_photo_btn;
     private Button select_photo_btn;
     private ImageView photo_iv;

     // 相機拍照
     public static final int TAKE_PHOTO_CODE = 1;
     // 相冊選圖
     public static final int SELECT_PIC_CODE = 2;
     // 圖片裁剪
     private static final int PHOTO_CROP_CODE = 3;

     private Uri photoUri;   // 圖片的 Uri
     private String picPath; // 圖片檔案路徑

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

     private void initViews() {
         this.take_photo_btn = (Button) findViewById(R.id.take_photo_btn);
         this.take_photo_btn.setOnClickListener(this);
         this.select_photo_btn = (Button) findViewById(R.id.select_photo_btn);
         this.select_photo_btn.setOnClickListener(this);
         this.photo_iv = (ImageView) findViewById(R.id.photo_iv);
     }

     @Override
     public void onClick(View view) {
         switch (view.getId()) {
             case R.id.take_photo_btn: // 拍照
                 picTyTakePhoto();
                 break;
             case R.id.select_photo_btn: // 選圖庫
                 pickPhoto();
                 break;
         }
     }

     /**
      * 拍照取得圖片
      */
     private void picTyTakePhoto() {
         // 先確認 SDCard 存在
         String SDState = Environment.getExternalStorageState();
         if (SDState.equals(Environment.MEDIA_MOUNTED)) {
             Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

             /**
              * 使用相機拍照,照片會存入相簿。
              * 這種方式的好處是:拿到的是拍照後的原圖。
              * 若不透過 ContentValues 保存照片路徑,拍照後取得的會是縮圖,可能不清晰。
              */
             ContentValues values = new ContentValues();
             photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
             intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
             startActivityForResult(intent, TAKE_PHOTO_CODE);
         } else {
             Toast.makeText(this, "內存卡不存在", Toast.LENGTH_LONG).show();
         }
     }

     /**
      * 從相冊取得圖片
      */
     private void pickPhoto() {
         Intent intent = new Intent(Intent.ACTION_PICK, null);
         intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
         startActivityForResult(intent, SELECT_PIC_CODE);
     }

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

         if (resultCode == Activity.RESULT_OK) {
             // 相冊選圖(部分機型有相容性問題,請留意)
             if (requestCode == SELECT_PIC_CODE) {
                 if (null != data && null != data.getData()) {
                     photoUri = data.getData();
                     picPath = uriToFilePath(photoUri);
                     startPhotoZoom(photoUri, PHOTO_CROP_CODE);
                 } else {
                     Toast.makeText(this, "圖片選擇失敗", Toast.LENGTH_LONG).show();
                 }
             }
             // 拍照回來
             else if (requestCode == TAKE_PHOTO_CODE) {
                 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);
                     if (Build.VERSION.SDK_INT < 14) {
                         cursor.close();
                     }
                 }
                 if (picPath != null) {
                     photoUri = Uri.fromFile(new File(picPath));
                     startPhotoZoom(photoUri, PHOTO_CROP_CODE);
                 } else {
                     Toast.makeText(this, "圖片選擇失敗", Toast.LENGTH_LONG).show();
                 }
             }
             // 裁剪完成
             else if (requestCode == PHOTO_CROP_CODE) {
                 if (photoUri != null) {
                     Bitmap bitmap = BitmapFactory.decodeFile(picPath);
                     if (bitmap != null) {
                         // 這裡可以把圖片上傳到伺服器
                         photo_iv.setImageBitmap(bitmap);
                     }
                 }
             }
         }
     }

     /**
      * 呼叫系統裁剪
      */
     private void startPhotoZoom(Uri uri, int REQUE_CODE_CROP) {
         Intent intent = new Intent("com.android.camera.action.CROP");
         intent.setDataAndType(uri, "image/*");
         intent.putExtra("crop", "true");            // 開啟裁剪模式
         intent.putExtra("scale", true);             // 去黑邊
         intent.putExtra("scaleUpIfNeeded", true);
         intent.putExtra("aspectX", 3);              // 寬高比例,依需求調整
         intent.putExtra("aspectY", 2);
         intent.putExtra("outputX", 600);            // 輸出的寬(像素)
         intent.putExtra("outputY", 400);            // 輸出的高(像素)
         intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
         intent.putExtra("noFaceDetection", true);   // 關閉人臉識別
         intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
         intent.putExtra("return-data", false);      // 不透過 data 回傳,避免 OOM
         startActivityForResult(intent, REQUE_CODE_CROP);
     }

     /**
      * Uri 轉檔案路徑
      */
     private String uriToFilePath(Uri uri) {
         String[] proj = { MediaStore.Images.Media.DATA };
         Cursor cursor = managedQuery(uri, proj, null, null, null);
         int image_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
         cursor.moveToFirst();
         return cursor.getString(image_index);
     }
 }

版面檔

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

     <Button
         android:id="@+id/take_photo_btn"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="20dp"
         android:gravity="center"
         android:text="拍照"
         android:textSize="16sp"/>

     <Button
         android:id="@+id/select_photo_btn"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="20dp"
         android:gravity="center"
         android:text="選擇圖片"
         android:textSize="16sp"/>

     <ImageView
         android:id="@+id/photo_iv"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center_horizontal"
         android:layout_marginTop="20dp"/>
 </LinearLayout>

別忘了權限

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

新版 Android 必須注意的三件事

  1. 執行期權限:Android 6.0 起,相機與儲存空間都是執行期權限,必須用 requestPermissions() 主動請求,並處理使用者拒絕的分支。
  2. FileProvider:Android 7.0 起禁止把 file:// URI 傳給其他 App,會直接拋 FileUriExposedException。必須改用 FileProvider.getUriForFile() 產生 content:// URI,並在 AndroidManifest.xml 宣告 provider 與 file_paths.xml。
  3. 別再用隱式 CROP Intent:com.android.camera.action.CROP 是非官方 action,越來越多機型(尤其原生 Android 11 以上)找不到對應的處理者。建議改用 uCrop、Android-Image-Cropper 這類專門的裁剪庫,API 更穩定,也能自行控制 UI。
  4. 分區儲存(Scoped Storage):Android 10 起對外部儲存空間的存取大幅收緊,寫入自己的 App 目錄或 MediaStore 才是長久之計,WRITE_EXTERNAL_STORAGE 也不再是萬靈丹。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved