標籤:android 圖片
Android開發過程中,我們經常需要擷取圖片,你可以通過擷取手機相簿的圖片,也可以調用相機拍照擷取圖片。這裡主要講這兩個擷取圖片的方式,並記錄其中遇到的小問題。
調用相簿擷取圖片
這個功能非常簡單,這裡不多說了,這裡貼出關鍵代碼
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);openAlbumIntent.setType("image/*");startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
其中CHOOSE_PICTURE是requestCode。執行上述代碼,然後在onActivityResult方法中接收返回資料
protected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubif (resultCode != RESULT_OK)return;switch (requestCode) {case CHOOSE_PICTURE:Uri uri = data.getData();try {if (photo != null)photo.recycle();photo = MediaStore.Images.Media.getBitmap(getContentResolver(),uri);System.out.println("bitmap size frome gallery = "+ Utils.getBitmapSize(photo));image.setImageBitmap(photo);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}break;default:break;}}
調用相機拍照擷取圖片
調用系統相機可以用以下兩種方式:
//指定拍照照片儲存路徑Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);cameraFile = DiskUtils.generatePhotoFile(this);cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(cameraFile));this.startActivityForResult(cameraintent, CAMERA_REQUEST);////,,,,,//不指定圖片儲存路徑Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);startActivityForResult(cameraIntent, CAMERANF_REQUEST);
調用相機拍照有兩點需要注意,
- 你可以指定拍照所得照片的儲存路徑,也可以不指定,直接獲得照片。二者區別在於後者會使照片失真(照片檔案小很多)
- 很多相機拍照之後,照片是旋轉90度的,所以需要處理照片角度
第二個問題可以這樣輕鬆解決
public static int readPictureDegree(String path) {int degree = 0;try {ExifInterface exifInterface = new ExifInterface(path);int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);switch (orientation) {case ExifInterface.ORIENTATION_ROTATE_90:degree = 90;break;case ExifInterface.ORIENTATION_ROTATE_180:degree = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:degree = 270;break;}} catch (IOException e) {e.printStackTrace();}return degree;}public static Bitmap rotateBitmap(Bitmap bitmap, float rotateDegree){Matrix matrix = new Matrix();matrix.postRotate((float)rotateDegree);bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);return bitmap;}
上面兩個方法分別是旋轉圖片,和計算圖片的角度,先調用第二個方法擷取圖片的角度,然後調用第第一個方法將圖片旋轉。
調用系統剪下圖片功能
有時你想要對圖片進行剪下,實現也很簡單,如下
首先執行以下代碼
// 圖片剪下private void startPhotoZoom(Uri uri) {Intent intent = new Intent("com.android.camera.action.CROP");intent.setDataAndType(uri, "image/*");// crop為true是設定在開啟的intent中設定顯示的view可以剪裁intent.putExtra("crop", "true");// aspectX aspectY 是寬高的比例intent.putExtra("aspectX", 0);intent.putExtra("aspectY", 0);// outputX,outputY 是剪裁圖片的寬高//intent.putExtra("outputX", 2000);//intent.putExtra("outputY", 2000);intent.putExtra("return-data", true);intent.putExtra("noFaceDetection", true);this.startActivityForResult(intent, CROP_2_REQUEST);}
然後再onActivityResult中接收資料
photo = data.getExtras().getParcelable("data");image.setImageBitmap(photo);
以下提供一個完整的例子,源碼地址 如下:
Android圖片系列(1)-------調用系統相簿與相機擷取圖片