android调用系统相机拍照后对相片进行裁剪

1.调用系统相机意图
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(FileUtil.isExists(FileUtil.PATH)){
    fileName = System.currentTimeMillis()+".jpg";
    //设置照相返回图片保存路径
    mPhotoFileUri = Uri.fromFile(new File(FileUtil.SDPATH+File.separator+FileUtil.PATH+File.separator+fileName));
    intent.putExtra(MediaStore.EXTRA_OUTPUT,mPhotoFileUri);
    startActivityForResult(intent,REQUEST_CODE_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK){
        filePath = mPhotoFileUri.getPath();
        Log.e(TAG, "onActivityResult: "+filePath);
        rotateImageIdNeed(filePath);
    }else if(requestCode == PHOTO_REQUEST_CUT && resultCode == RESULT_OK && data != null){
 //imagview来显示裁剪后的图片
 mCarPhoto.setImageBitmap(BitmapFactory
            .decodeFile(smallFilePath));
    if (mPhotoFileUri != null) {
        File file = new File(mPhotoFileUri.getPath());
        if (file != null && file.exists()) {
            file.delete();
        }
    }
    mPhotoFileUri = null;
}
}}
不同的型号的手机拍照后得到的图片的角度不同,正常情况下是0度,有的相机拍照后的照片可能旋转90度,所以,裁剪前,要对
要裁剪的照片进行旋转。
/**旋转图片*/
private void rotateImageIdNeed(String filePath) {
    try {
        int degree = 0;
        ExifInterface exifInterface = new ExifInterface(filePath);//获得图片的前缀
        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;
        }
        if(degree!=0){
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(path, options);
                    int width = options.outWidth;
                    int height = options.outHeight;
                    float hh = 360.0f;
                    float ww = 360.0f;
                    int be = 1;// be=1表示不缩放
                    if (width > height && width > ww) {// 如果 宽度大于高度并且
                                                        // 宽度大于固定宽度时缩放
                        be = (int) (width / ww) + 1;
                    }
                    if (height > width && height > hh) {// 如果 高度大于宽度并且
                                                        // 高度大于国定高度时缩放
                        be = (int) (height / hh) + 1;
                    }
                    if (be <= 0) {
                        be = 1;
                    }
                    options.inSampleSize = be;
                    options.inJustDecodeBounds = false;
                  
                    bitmap = BitmapFactory.decodeFile(filePath,options);
            //旋转图片动作
            Matrix matrix = new Matrix();
            matrix.postRotate(degree);
            //创建新图片
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
            FileUtil.saveBitmap2File(resizedBitmap,filePath,100);
            if (mHandler != null) {
                mHandler.sendEmptyMessage(MSG_TO_CROP_IMAGE);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
这里用到了handler发送一个裁剪意图,在handler里去处理裁剪,这里用到WeakReference弱引用,来防止内存溢出。想了解
弱引用的使用,请看我下一篇博客。
private class InnerHandler extends Handler{
    private WeakReference mRef;
    public InnerHandler(HeadActivity obj){
        mRef = new WeakReference(obj);
    }

    @Override
    public void handleMessage(Message msg) {
        if(mRef == null || mRef.get() == null){
                return ;
        }
        if(msg.what == PHOTO_REQUEST_CUT){
            mRef.get().cropPhoto();
        }
    }
}
public void cropPhoto(){
    startPhotoZoom(mPhotoFileUri);
}
下面开始真正的图片的裁剪
/**开始剪切图片*/
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",1);
    intent.putExtra("aspectY",1);
    // outputX outputY 是裁剪图片宽高
    intent.putExtra("outputX", 800);
    intent.putExtra("outputY", 800);
    //是否将数据保留在Bitmap中返回
    intent.putExtra("return-data", false);
    // 当图片的宽高不足时,会出现黑边,去除黑边
    intent.putExtra("scale", true);
    intent.putExtra("scaleUpIfNeeded", true);
    smallFilePath = FileUtil.SDPATH + File.separator + FileUtil.PATH
            + File.separator + System.currentTimeMillis() + ".jpg";
    intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(smallFilePath)));
    intent.putExtra("outputFormat", "JPEG");// 返回格式
    startActivityForResult(intent,PHOTO_REQUEST_CUT);
}
下面是FileUtils里的代码
public class FileUtil {
    public static final String SDPATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static final String PATH = "congmingtou";

    /**
     * 是否支持SDCard
     */
    public static boolean isSupportSDCard() {
        return Environment.getExternalStorageDirectory().exists();
    }

    /**
     * 检测文件或者路径是否存在
     * 

* 可以给值为Null,如果给值null,判断路径是否存在 */ public static boolean isExists(String path, String fileName) { if (null == path && null == fileName) { return false; } String name; name = SDPATH + File.separator + path; File file = new File(name); if (!file.exists()) { file.mkdirs(); } File fileNmae = new File(name, fileName); return fileNmae.exists(); } public static boolean isExists(String path) { if (null == path) { return false; } String name; name = SDPATH + File.separator + path; File file = new File(name); if (!file.exists()) { file.mkdirs(); } return file.exists(); } /** * 检查SD卡是否可用 */ public static boolean isAvailable() { return Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState()); } /*** *保存bitmap对象到文件中 * @param bm * @param path * @param quality * @return */ public static boolean saveBitmap2File(Bitmap bm, String path, int quality) { if (null == bm || bm.isRecycled()) { return false; } try { File file = new File(path); if (file.exists()) { file.delete(); } BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file)); bm.compress(Bitmap.CompressFormat.JPEG, quality, bos); bos.flush(); bos.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { if (null != bm) { if (!bm.isRecycled()) { bm.recycle(); } bm = null; } } } }



 
  










你可能感兴趣的:(android调用系统相机拍照后对相片进行裁剪)