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

Android 圖片處理實戰:拍照、相冊選擇與裁剪的完整封裝

編輯:關於 Android 程式設計

幾乎每個 App 都會遇到「更換頭像」這類需求:使用者可以拍照,也可以從相冊挑一張,最後再裁成固定比例。本文把整個流程做出一個可重複使用的元件,並示範如何整合 uCrop 做高品質裁剪。

一、最終效果

先看一下要達到的樣子:點擊頭像後彈出一個底部選擇框,可選「拍照/從相冊選擇/取消」,選好圖片後進入裁剪頁,完成後回填到畫面。

  

二、為什麼選 Android-Crop

Yalantis 的 uCrop 動畫效果很精緻,但原始碼在客製化界面上留有不少限制。於是在其基礎上延伸出 Android-Crop,把「界面定制」獨立出來,讓開發者能自由替換樣式。下圖就是用它模仿微信風格挑圖並裁剪的示範。

   

三、整體思路

核心其實只有兩條路:一是直接選裝置裡的既有圖片,裁完存到指定路徑;二是呼叫系統相機拍照,先把照片暫存到 SD 卡,再走同一套裁剪流程。兩條路最後都匯流到「裁剪並保存」。

    

四、用 PopupWindow 做選擇框

選擇框用 PopupWindow 實作最直接,效果如下:

   

1. 先寫好 XML 佈局,三顆按鈕分別對應拍照、相冊與取消:

<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/pop_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#444"
        android:gravity="center_horizontal"
        android:orientation="vertical">
        <Button android:id="@+id/picture_selector_take_photo_btn"
            android:text="拍照" ... />
        <Button android:id="@+id/picture_selector_pick_picture_btn"
            android:text="從相冊選擇" ... />
        <Button android:id="@+id/picture_selector_cancel_btn"
            android:text="取消" ... />
    </LinearLayout>
</RelativeLayout>

2. 在 PopupWindow 子類別的建構子裡載入佈局並綁定監聽:

public SelectPicturePopupWindow(Context context) {
    super(context);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mMenuView = inflater.inflate(R.layout.layout_picture_selector, null);
    takePhotoBtn = (Button) mMenuView.findViewById(R.id.picture_selector_take_photo_btn);
    pickPictureBtn = (Button) mMenuView.findViewById(R.id.picture_selector_pick_picture_btn);
    cancelBtn = (Button) mMenuView.findViewById(R.id.picture_selector_cancel_btn);
    takePhotoBtn.setOnClickListener(this);
    pickPictureBtn.setOnClickListener(this);
    cancelBtn.setOnClickListener(this);
}

為了讓外部能收到點擊結果,定義一個回呼介面,回傳被點的 View 與索引:

public interface OnSelectedListener {
    void OnSelected(View v, int position);
}
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.picture_selector_take_photo_btn:
            if (null != mOnSelectedListener) mOnSelectedListener.OnSelected(v, 0);
            break;
        case R.id.picture_selector_pick_picture_btn:
            if (null != mOnSelectedListener) mOnSelectedListener.OnSelected(v, 1);
            break;
        case R.id.picture_selector_cancel_btn:
            if (null != mOnSelectedListener) mOnSelectedListener.OnSelected(v, 2);
            break;
    }
}

3. 提供顯示與移除兩個方法即可對外使用:

public void showPopupWindow(Activity activity) {
    popupWindow = new PopupWindow(mMenuView,
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    popupWindow.showAtLocation(activity.getWindow().getDecorView(),
            Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    popupWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
    popupWindow.setFocusable(false);
    popupWindow.update();
}

public void dismissPopupWindow() {
    if (popupWindow != null && popupWindow.isShowing()) {
        popupWindow.dismiss();
        popupWindow = null;
    }
}

五、使用選擇框

封裝好之後,初始化加上設定監聽就能用:

mSelectPicturePopupWindow = new SelectPicturePopupWindow(mContext);
mSelectPicturePopupWindow.setOnSelectedListener(this);

六、拍照並保存

用 MediaStore.ACTION_IMAGE_CAPTURE 呼叫系統相機,並以 EXTRA_OUTPUT 指定輸出路徑(此處存到 SD 卡根目錄):

Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath)));
startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
// mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";

七、從相冊選擇

Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(pickIntent, GALLERY_REQUEST_CODE);

八、以 uCrop 裁剪

把比例設為 1:1、最大輸出 512×512,其餘可依需求調整:

public void startCropActivity(Uri uri) {
    UCrop.of(uri, mDestinationUri)
        .withAspectRatio(1, 1)
        .withMaxResultSize(512, 512)
        .withTargetActivity(CropActivity.class)
        .start(mActivity, this);
}

拍照與相冊兩條路徑在 onActivityResult 中統一導向裁剪:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == mActivity.RESULT_OK) {
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:
                startCropActivity(Uri.fromFile(new File(mTempPhotoPath)));
                break;
            case GALLERY_REQUEST_CODE:
                startCropActivity(data.getData());
                break;
            case UCrop.REQUEST_CROP:
                // 裁剪成功
                break;
            case UCrop.RESULT_ERROR:
                // 裁剪失敗
                break;
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

CropActivity 的樣式可以很簡潔,也可以自由換妝:

裁剪頁的佈局核心只有一個 UCropView:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:fab="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="true"
    android:fitsSystemWindows="true">
    <include layout="@layout/toolbar_layout" />
    <FrameLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar"
        android:background="#000">
        <com.kevin.crop.view.UCropView android:id="@+id/weixin_act_ucrop"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible" />
    </FrameLayout>
    <android.support.design.widget.CoordinatorLayout ...>
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/crop_act_save_fab"
            android:layout_gravity="bottom|right"
            android:src="@mipmap/ic_done_white" ... />
    </android.support.design.widget.CoordinatorLayout>
</RelativeLayout>

初始化時取出 CropImageView 與 OverlayView 並做基本設定(允許縮放、禁止旋轉、顯示裁剪框、隱藏網格等),再依 Intent 帶入的比例與最大尺寸參數套用即可。裁剪保存的關鍵片段如下:

private void cropAndSaveImage() {
    OutputStream outputStream = null;
    try {
        final Bitmap croppedBitmap = mGestureCropImageView.cropImage();
        if (croppedBitmap != null) {
            outputStream = getContentResolver().openOutputStream(mOutputUri);
            croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
            croppedBitmap.recycle();
            setResultUri(mOutputUri, mGestureCropImageView.getTargetAspectRatio());
            finish();
        } else {
            setResultException(new NullPointerException("cropImage() returned null."));
        }
    } catch (Exception e) {
        setResultException(e);
        finish();
    } finally {
        BitmapLoadUtils.close(outputStream);
    }
}

成功與失敗的分別處理:

private void handleCropResult(Intent result) {
    deleteTempPhotoFile();
    final Uri resultUri = UCrop.getOutput(result);
    if (null != resultUri && null != mOnPictureSelectedListener) {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(mActivity.getContentResolver(), resultUri);
        mOnPictureSelectedListener.onPictureSelected(resultUri, bitmap);
    } else {
        Toast.makeText(mContext, "無法剪切選擇圖片", Toast.LENGTH_SHORT).show();
    }
}

再定義一個對外回呼介面,讓使用端只要拿到 Uri 與 Bitmap 就能更新畫面:

public interface OnPictureSelectedListener {
    void onPictureSelected(Uri fileUri, Bitmap bitmap);
}

九、使用方式

把上述邏輯收攏進 PictureSelectFragment 後,使用端只要繼承它並設定監聽即可:

setOnPictureSelectedListener(new OnPictureSelectedListener() {
    @Override
    public void onPictureSelected(Uri fileUri, Bitmap bitmap) {
        mPictureIv.setImageBitmap(bitmap);
        Toast.makeText(mContext, "圖片已經保存到:" + Uri.decode(fileUri.getEncodedPath()), Toast.LENGTH_LONG).show();
    }
});

透過這樣的封裝與基類抽取,之後任何頁面要加「更換頭像」功能,幾行程式碼就能搞定,不必每次重寫拍照、選圖與裁剪的細節。

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