1. 程式人生 > >Android 實現拍照,選擇圖片並剪下儲存

Android 實現拍照,選擇圖片並剪下儲存

專案中有一個實現圖片的剪下功能和APP“酷站”的點選中間“+”字元,進行圖片選擇到最後剪下功能;“微信”選擇圖片並剪下類似 ,由於測試的模擬器中沒有圖片,所以把參考資料上圖片截下來展示下:

查了一些參考資料,使用的而並不是Android系統的圖片剪下方法,而是UCrop庫的封裝,或自定義的高仿微信圖片剪下:(請詳細參考資料)

選擇框實現:

xml佈局:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:gravity="center_horizontal"
 android:orientation="vertical"> 
  
 <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:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginLeft="10dip"
 android:layout_marginRight="10dip"
 android:layout_marginTop="10dp"
 android:background="#4d69ff"
 android:padding="10dp"
 android:text="拍照"
 android:textColor="#CEC9E7"
 android:textSize="18sp"
 android:textStyle="bold" /> 
  
 <Button
 android:id="@+id/picture_selector_pick_picture_btn"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginLeft="10dip"
 android:layout_marginRight="10dip"
 android:layout_marginTop="5dp"
 android:background="#4d69ff"
 android:padding="10dp"
 android:text="從相簿選擇"
 android:textColor="#CEC9E7"
 android:textSize="18sp"
 android:textStyle="bold" /> 
  
 <Button
 android:id="@+id/picture_selector_cancel_btn"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginBottom="15dip"
 android:layout_marginLeft="10dip"
 android:layout_marginRight="10dip"
 android:layout_marginTop="20dp"
 android:background="@android:color/white"
 android:padding="10dp"
 android:text="取消"
 android:textColor="#373447"
 android:textSize="18sp"
 android:textStyle="bold" /> 
 </LinearLayout> 
  
</RelativeLayout> 

程式碼片段:
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); 
}
建立SelectPicturePopupWindow的時候設定按鈕的監聽。這裡編寫一個選擇監聽介面:
/** 
 * 選擇監聽介面 
 */
public interface OnSelectedListener { 
 void OnSelected(View v, int position); 
} 
回撥的引數為點選的按鈕View以及當前按鈕的索引,那麼只要在選擇監聽裡面返回介面的回撥就可以啦。
@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; 
 } 
} 
PopupWindow的初始化建立、監聽設定好之後,只要提供顯示與隱藏兩個方法就可以了。
/** 
 * 把一個View控制元件新增到PopupWindow上並且顯示 
 * 
 * @param activity 
 */
public void showPopupWindow(Activity activity) { 
 popupWindow = new PopupWindow(mMenuView, // 新增到popupWindow 
 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 
 popupWindow.update(); 
} 
/** 
 * 移除PopupWindow 
 */
public void dismissPopupWindow() { 
 if (popupWindow != null && popupWindow.isShowing()) { 
 popupWindow.dismiss(); 
 popupWindow = null; 
 } 
}

使用選擇框

通過我們上面對選擇框的封裝,使用起來就比較簡單了,只需要初始化及設定選擇的監聽就可以啦。

初始化選擇框:

mSelectPicturePopupWindow = new SelectPicturePopupWindow(mContext); 
mSelectPicturePopupWindow.setOnSelectedListener(this); 
設定選擇框的監聽:
@Override
public void OnSelected(View v, int position) { 
 switch (position) { 
 case 0: 
 // TODO: "拍照"按鈕被點選了 
 break; 
 case 1: 
 // TODO: "從相簿選擇"按鈕被點選了 
 break; 
 case 2: 
 // TODO: "取消"按鈕被點選了 
 break; 
 } 
} 
然後在Fragment上進行封裝,我們取名為PictureSelectFragment。

拍照並儲存圖片

呼叫系統的拍照,並把拍攝的圖片儲存到指定位置。

@Override
public void OnSelected(View v, int position) { 
 switch (position) { 
 case 0: 
 // "拍照"按鈕被點選了 
 mSelectPicturePopupWindow.dismissPopupWindow(); 
 Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
 //下面這句指定呼叫相機拍照後的照片儲存的路徑 
 takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath))); 
 startActivityForResult(takeIntent, CAMERA_REQUEST_CODE); 
 break; 
 case 1: 
 // TODO: "從相簿選擇"按鈕被點選了 
 break; 
 case 2: 
 // TODO: "取消"按鈕被點選了 
 break; 
 } 
} 

這裡的指定位置為sd卡本目錄下
mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg"; 

當拍攝照片完成時會回撥到onActivityResult,我們在這裡處理圖片的裁剪就可以了。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
 if (resultCode == mActivity.RESULT_OK) { 
 switch (requestCode) { 
 case CAMERA_REQUEST_CODE: 
 // TODO: 呼叫相機拍照 
 break; 
 } 
 } 
 super.onActivityResult(requestCode, resultCode, data); 
} 

相簿選擇圖片

呼叫系統的選擇圖片

@Override
public void OnSelected(View v, int position) { 
 switch (position) { 
 case 0: 
 // "拍照"按鈕被點選了 
 mSelectPicturePopupWindow.dismissPopupWindow(); 
 Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
 // 下面這句指定呼叫相機拍照後的照片儲存的路徑 
 takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath))); 
 startActivityForResult(takeIntent, CAMERA_REQUEST_CODE); 
 break; 
 case 1: 
 // "從相簿選擇"按鈕被點選了 
 mSelectPicturePopupWindow.dismissPopupWindow(); 
 Intent pickIntent = new Intent(Intent.ACTION_PICK, null); 
 // 如果限制上傳到伺服器的圖片型別時可以直接寫如:"image/jpeg 、 image/png等的型別" 
 pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); 
 startActivityForResult(pickIntent, GALLERY_REQUEST_CODE); 
 break; 
 case 2: 
 // TODO: "取消"按鈕被點選了 
 break; 
 } 
} 
當拍選擇圖片完成時會回撥到onActivityResult,在這裡處理選擇的返回結果
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
 if (resultCode == mActivity.RESULT_OK) { 
 switch (requestCode) { 
 case CAMERA_REQUEST_CODE: 
 // TODO: 呼叫相機拍照 
 break; 
 case GALLERY_REQUEST_CODE: 
 // TODO: 直接從相簿獲取 
 break; 
 } 
 } 
 super.onActivityResult(requestCode, resultCode, data); 
} 
使用Crop裁剪圖片

裁剪圖片,這裡設定寬高比為1:1,最大尺寸為512*512,當然可以根據自己的需求來設定。

/** 
 * 裁剪圖片方法實現 
 * 
 * @param uri 
 */
public void startCropActivity(Uri uri) { 
 UCrop.of(uri, mDestinationUri) 
 .withAspectRatio(1, 1) 
 .withMaxResultSize(512, 512) 
 .withTargetActivity(CropActivity.class) 
 .start(mActivity, this); 
} 
當然,這裡的比例你也可以設定成其他的,3:4  ,4:3 等等
CropActiivty裁剪完成時會回撥到onActivityResult,在這裡處理選擇的返回結果。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
 if (resultCode == mActivity.RESULT_OK) { 
 switch (requestCode) { 
 case CAMERA_REQUEST_CODE: // 呼叫相機拍照 
 File temp = new File(mTempPhotoPath); 
 startCropActivity(Uri.fromFile(temp)); 
 break; 
 case GALLERY_REQUEST_CODE: // 直接從相簿獲取 
 startCropActivity(data.getData()); 
 break; 
 case UCrop.REQUEST_CROP: 
 // TODO: 裁剪圖片結果 
 break; 
 case UCrop.RESULT_ERROR: 
 // TODO: 裁剪圖片錯誤 
 break; 
 } 
 } 
 super.onActivityResult(requestCode, resultCode, data); 
} 
CropActivity的介面如下所示:



當然也可以輕鬆設計成如下兩圖:



xml佈局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:fab="http://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:layout_width="match_parent"
 android:layout_height="match_parent"> 
  
 <android.support.design.widget.FloatingActionButton
 android:id="@+id/crop_act_save_fab"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="bottom|right"
 android:layout_margin="@dimen/fab_margin"
 android:src="@mipmap/ic_done_white"
 fab:fabSize="normal" /> 
 </android.support.design.widget.CoordinatorLayout> 
  
  
</RelativeLayout> 

可以發現非常簡單,只有一個主要的CropView,這就是uCrop框架為我們提供的

程式碼片段:

@Override
protected void initViews() { 
 initToolBar(); 
  
 mGestureCropImageView = mUCropView.getCropImageView(); 
 mOverlayView = mUCropView.getOverlayView(); 
  
 // 設定允許縮放 
 mGestureCropImageView.setScaleEnabled(true); 
 // 設定禁止旋轉 
 mGestureCropImageView.setRotateEnabled(false); 
 // 設定外部陰影顏色 
 mOverlayView.setDimmedColor(Color.parseColor("#AA000000")); 
 // 設定周圍陰影是否為橢圓(如果false則為矩形) 
 mOverlayView.setOvalDimmedLayer(false); 
 // 設定顯示裁剪邊框 
 mOverlayView.setShowCropFrame(true); 
 // 設定不顯示裁剪網格 
 mOverlayView.setShowCropGrid(false); 
  
 final Intent intent = getIntent(); 
 setImageData(intent); 
} 
private void setImageData(Intent intent) { 
 Uri inputUri = intent.getParcelableExtra(UCrop.EXTRA_INPUT_URI); 
 mOutputUri = intent.getParcelableExtra(UCrop.EXTRA_OUTPUT_URI); 
  
 if (inputUri != null && mOutputUri != null) { 
 try { 
 mGestureCropImageView.setImageUri(inputUri); 
 } catch (Exception e) { 
 setResultException(e); 
 finish(); 
 } 
 } else { 
 setResultException(new NullPointerException("Both input and output Uri must be specified")); 
 finish(); 
 } 
  
 // 設定裁剪寬高比 
 if (intent.getBooleanExtra(UCrop.EXTRA_ASPECT_RATIO_SET, false)) { 
 float aspectRatioX = intent.getFloatExtra(UCrop.EXTRA_ASPECT_RATIO_X, 0); 
 float aspectRatioY = intent.getFloatExtra(UCrop.EXTRA_ASPECT_RATIO_Y, 0); 
  
 if (aspectRatioX > 0 && aspectRatioY > 0) { 
 mGestureCropImageView.setTargetAspectRatio(aspectRatioX / aspectRatioY); 
 } else { 
 mGestureCropImageView.setTargetAspectRatio(CropImageView.SOURCE_IMAGE_ASPECT_RATIO); 
 } 
 } 
  
 // 設定裁剪的最大寬高 
 if (intent.getBooleanExtra(UCrop.EXTRA_MAX_SIZE_SET, false)) { 
 int maxSizeX = intent.getIntExtra(UCrop.EXTRA_MAX_SIZE_X, 0); 
 int maxSizeY = intent.getIntExtra(UCrop.EXTRA_MAX_SIZE_Y, 0); 
  
 if (maxSizeX > 0 && maxSizeY > 0) { 
 mGestureCropImageView.setMaxResultImageSizeX(maxSizeX); 
 mGestureCropImageView.setMaxResultImageSizeY(maxSizeY); 
 } else { 
 Log.w(TAG, "EXTRA_MAX_SIZE_X and EXTRA_MAX_SIZE_Y must be greater than 0"); 
 } 
 } 
} 
以上為CropView的配置,更多配置請參考專案原始碼。

最重要的,裁剪儲存圖片:

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("CropImageView.cropImage() returned null.")); 
 } 
 } catch (Exception e) { 
 setResultException(e); 
 finish(); 
 } finally { 
 BitmapLoadUtils.close(outputStream); 
 } 
} 
處理裁剪失敗的返回值
/** 
 * 處理剪下失敗的返回值 
 * 
 * @param result 
 */
private void handleCropError(Intent result) { 
 deleteTempPhotoFile(); 
 final Throwable cropError = UCrop.getError(result); 
 if (cropError != null) { 
 Log.e(TAG, "handleCropError: ", cropError); 
 Toast.makeText(mContext, cropError.getMessage(), Toast.LENGTH_LONG).show(); 
 } else { 
 Toast.makeText(mContext, "無法剪下選擇圖片", Toast.LENGTH_SHORT).show(); 
 } 
} 
這裡設定了選擇的回撥介面,便於封裝抽取。
/** 
 * 圖片選擇的回撥介面 
 */
public interface OnPictureSelectedListener { 
 /** 
 * 圖片選擇的監聽回撥 
 * 
 * @param fileUri 
 * @param bitmap 
 */
 void onPictureSelected(Uri fileUri, Bitmap bitmap); 
} 
我們的PictureSelectFragment就搞定了,在使用的時候只要繼承它,幾行程式碼就搞定了。

PictureSelectFragment使用

// 設定圖片點選監聽 
mPictureIv.setOnClickListener(new View.OnClickListener() { 
 @Override
 public void onClick(View v) { 
 selectPicture(); 
 } 
}); 

// 設定裁剪圖片結果監聽 
setOnPictureSelectedListener(new OnPictureSelectedListener() { 
 @Override
 public void onPictureSelected(Uri fileUri, Bitmap bitmap) { 
 mPictureIv.setImageBitmap(bitmap); 
  
 String filePath = fileUri.getEncodedPath(); 
 String imagePath = Uri.decode(filePath); 
 Toast.makeText(mContext, "圖片已經儲存到:" + imagePath, Toast.LENGTH_LONG).show(); 
 } 
});