有時候我們需要的圖片並不適合我們想要的大小, 那么我們就可以用到系統自帶的圖片裁剪功能, 把規定范圍的圖像給剪出來。
貼上部分代碼:
- //調用圖庫
- Intent intent = new Intent();
- intent.setType("image/*");
- intent.putExtra("crop", "true"); // crop=true 有這句才能出來最后的裁剪頁面.
- intent.putExtra("aspectX", 5); // 這兩項為裁剪框的比例.
- intent.putExtra("aspectY", 4);
- //輸出地址
- intent.putExtra("output", Uri.fromFile(new File("SDCard/1.jpg")
- intent.putExtra("outputFormat", "JPEG");//返回格式
- startActivityForResult(Intent.createChooser(intent, "選擇圖片"), 1);
- //調用相機
- Intent intent = new Intent(
- MediaStore.ACTION_IMAGE_CAPTURE, null);
- intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
- "SDCard/1.jpg")));
- startActivityForResult(intent, 2);
在調用了以上任意一種方法后, 系統會返回onActivityResult, 我們在這個方法中處理就可以了
- /**
- * 獲取返回的相片
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data)
- {
- if (resultCode == 0)
- return;
- if (requestCode == 2)//調用系統裁剪
- {
- File picture = new File("SDCard/1.jpg");
- startPhotoZoom(Uri.fromFile(picture));
- } else if (requestCode == PHOTO_CODE)//得到裁剪后的圖片
- {
- try
- {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inSampleSize = 2;
- Bitmap bitmap = BitmapFactory.decodeFile("SDCard/1.jpg", options);
- if (bitmap != null)//保存圖片
- {
- mCacheBitmap = bitmap;
- FileOutputStream fos = null;
- fos = new FileOutputStream("SDCard/1.jpg");
- mCacheBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
- }
- } catch (Exception e)
- {
- // TODO: handle exception
- }
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- /**
- * 裁剪圖片
- * @param uri
- */
- public void startPhotoZoom(Uri uri) {
- Intent intent = new Intent("com.android.camera.action.CROP");
- intent.setDataAndType(uri, "image/*");
- intent.putExtra("crop", "true");// crop=true 有這句才能出來最后的裁剪頁面.
- intent.putExtra("aspectX", 5);// 這兩項為裁剪框的比例.
- intent.putExtra("aspectY", 4);// x:y=1:2
- intent.putExtra("output", Uri.fromFile(new File("SDCard/1.jpg")));
- intent.putExtra("outputFormat", "JPEG");//返回格式
- startActivityForResult(intent, PHOTO_CODE);