Android中获取图片进行裁剪功能的细节分析

需求描述:
在很多时候,我们需要在APP中调用摄像头拍摄相片或者选取本地相册中的图片进行裁剪,然后将裁剪后的图片上传至后台服务器。这方面有很多种实现方法,所以不再罗列,我只将我在这方面遇到的一些细节优化的地方总结一下。


关于裁剪
用的是https://github.com/jdamcd/android-crop, above API-14。这个开源代码将Itent封装的比较好。

工具入口是:

public class Crop {
    public static final int REQUEST_CAPTURE = 1216;
    public static final int REQUEST_CROP = 6709;
    public static final int REQUEST_PICK = 9162;
    public static final int RESULT_ERROR = 404;

    static interface Extra {
        String ASPECT_X = "aspect_x";
        String ASPECT_Y = "aspect_y";
        String MAX_X = "max_x";
        String MAX_Y = "max_y";
        String ERROR = "error";
    }

    private Intent cropIntent;

    /**
     * Create a crop Intent builder with source and destination image Uris
     *
     * @param source Uri for image to crop
     * @param destination Uri for saving the cropped image
     */
    public static Crop of(Uri source, Uri destination) {
        return new Crop(source, destination);
    }

    private Crop(Uri source, Uri destination) {
        cropIntent = new Intent();
        cropIntent.setData(source);
        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, destination);
    }

    /**
     * Set fixed aspect ratio for crop area
     * 自定义宽高比
     * @param x Aspect X
     * @param y Aspect Y
     */
    public Crop withAspect(int x, int y) {
        cropIntent.putExtra(Extra.ASPECT_X, x);
        cropIntent.putExtra(Extra.ASPECT_Y, y);
        return this;
    }

    /**
     * Crop area with fixed 1:1 aspect ratio
     * 默认一比一宽高比
     */
    public Crop asSquare() {
        cropIntent.putExtra(Extra.ASPECT_X, 1);
        cropIntent.putExtra(Extra.ASPECT_Y, 1);
        return this;
    }

    /**
     * Set maximum crop size
     *
     * @param width Max width
     * @param height Max height
     */
    public Crop withMaxSize(int width, int height) {
        cropIntent.putExtra(Extra.MAX_X, width);
        cropIntent.putExtra(Extra.MAX_Y, height);
        return this;
    }

    /**
     * Send the crop Intent from an Activity
     *
     * @param activity Activity to receive result
     */
    public void start(Activity activity) {
        start(activity, REQUEST_CROP);
    }

    /**
     * Send the crop Intent from an Activity with a custom requestCode
     *
     * @param activity Activity to receive result
     * @param requestCode requestCode for result
     */
    public void start(Activity activity, int requestCode) {
        activity.startActivityForResult(getIntent(activity), requestCode);
    }

    /**
     * Send the crop Intent from a Fragment
     *
     * @param context Context
     * @param fragment Fragment to receive result
     */
    public void start(Context context, Fragment fragment) {
        start(context, fragment, REQUEST_CROP);
    }

    /**
     * Send the crop Intent from a support library Fragment
     *
     * @param context Context
     * @param fragment Fragment to receive result
     */
    public void start(Context context, android.support.v4.app.Fragment fragment) {
        start(context, fragment, REQUEST_CROP);
    }

    /**
     * Send the crop Intent with a custom requestCode
     *
     * @param context Context
     * @param fragment Fragment to receive result
     * @param requestCode requestCode for result
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void start(Context context, Fragment fragment, int requestCode) {
        fragment.startActivityForResult(getIntent(context), requestCode);
    }

    /**
     * Send the crop Intent with a custom requestCode
     *
     * @param context Context
     * @param fragment Fragment to receive result
     * @param requestCode requestCode for result
     */
    public void start(Context context, android.support.v4.app.Fragment fragment, int requestCode) {
        fragment.startActivityForResult(getIntent(context), requestCode);
    }

    /**
     * Get Intent to start crop Activity
     *
     * @param context Context
     * @return Intent for CropImageActivity
     */
    public Intent getIntent(Context context) {
        cropIntent.setClass(context, CropImageActivity.class);
        return cropIntent;
    }

    /**
     * Retrieve URI for cropped image, as set in the Intent builder
     *
     * @param result Output Image URI
     */
    public static Uri getOutput(Intent result) {
        return result.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
    }

    /**
     * Retrieve error that caused crop to fail
     *
     * @param result Result Intent
     * @return Throwable handled in CropImageActivity
     */
    public static Throwable getError(Intent result) {
        return (Throwable) result.getSerializableExtra(Extra.ERROR);
    }

    /**
     * Utility to start an image picker
     *
     * @param activity Activity that will receive result
     */
    public static void pickImage(Activity activity) {
        pickImage(activity, REQUEST_PICK);
    }

    /**
     * Utility to start an image picker with request code
     *
     * @param activity Activity that will receive result
     * @param requestCode requestCode for result
     */
    public static void pickImage(Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*");
        try {
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, R.string.crop__pick_error, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 拍照获取
     * @param activity
     * 需要在Intent中加入保存的SD卡路径,否则onActivityResult中的得到的data图片会压缩很小
     */
    public static void pickCAPTURE(Activity activity, Uri path) {
        pickCAPTURE(activity, path, REQUEST_CAPTURE);
    }

    public static void pickCAPTURE(Activity activity, Uri path, int requestCode){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, path);
        try {
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, R.string.crop__pick_error, Toast.LENGTH_SHORT).show();
        }
    }
}

当然你也可以不用这个,用SDK本身的裁剪功能就可以了,同样可以在onActivityResult中返回得到裁剪的图片,而且可以自定义裁剪尺寸:

   private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 0.7);
        intent.putExtra("outputX", 1080);
        intent.putExtra("outputY", 756);
        intent.putExtra("return-data", true);
        getActivity().startActivityForResult(intent, 3);
    }

关于Uri、Bitmap、以及保存路径的转换
提供一个工具类:

public class UtilsImageProcess {

    /**
     * 将得到的一个Bitmap保存到SD卡上,得到一个URI地址
     */
    public static Uri saveBitmap(Bitmap bm) {
        //在SD卡上创建目录
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/org.chenlijian.test");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }

        File img = new File(tmpDir.getAbsolutePath() + "test.png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将得到的一个Bitmap保存到SD卡上,得到一个绝对路径
     */
    public static String getPath(Bitmap bm) {
        //在SD卡上创建目录
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/org.chenlijian.test");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }

        File img = new File(tmpDir.getAbsolutePath() + "/test.png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return img.getCanonicalPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将图库中选取的图片的URI转化为URI
     */
    public static Uri convertUri(Uri uri, Context context) {
        InputStream is;
        try {
            is = context.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 在拍摄照片之前生成一个文件路径Uri,保证拍出来的照片没有被压缩太小,用日期作为文件名,确保唯一性
     */
    public static String getSavePath(){
        String saveDir = Environment.getExternalStorageDirectory() + "/org.chenlijian.test";
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdir();
        }
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String fileName = saveDir + "/" + formatter.format(date) + ".png";

        return fileName;
    }

    /**
     *  计算图片的缩放值
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height/ (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     *  根据路径获得图片并压缩,返回bitmap用于显示
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        // 设置为true,画质更好一点,加载时间略长
        options.inPreferQualityOverSpeed = true;

        return BitmapFactory.decodeFile(filePath, options);
    }
}

关于拍照
通过拍照Intent,然后onActivityResult得到图片样张,再对其进行裁剪。一般得到的图片都很小,是因为经过了压缩,所以为了不让其压缩,需要在拍照Intent中加入保存的SD卡路径,然后在onActivityResult中得到的data为null,我们直接获取之前设置的SD卡路径的图片对其进行裁剪即可。当然不进行压缩图片肯定很大,之后我们可以根据自己的需求进行压缩。代码上面已经贴出来了。


示例

选择获取图片方式:

        case R.id.btn_dialog_one_select_img:
            imgDialog.dismiss();
            path_name = UtilsImageProcess.getSavePath();
            Crop.pickCAPTURE(getActivity(), Uri.fromFile(new File(path_name)));
            break;

        case R.id.btn_dialog_two_select_img:
            imgDialog.dismiss();
            Crop.pickImage(getActivity());
            break;

返回处理结果:

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {

        if (requestCode == Crop.REQUEST_CAPTURE) {    //拍照得到URI

            Bitmap bitmap = UtilsImageProcess.getSmallBitmap(path_name);
            Uri source = UtilsImageProcess.saveBitmap(bitmap);
            beginCrop(source);

        } else if (requestCode == Crop.REQUEST_PICK && data != null) {    //从相册中选取得到得到图片

            Uri source = UtilsImageProcess.convertUri(data.getData(), getActivity());
            beginCrop(source);

        } else if (requestCode == Crop.REQUEST_CROP && data != null) {     //得到裁剪后的图片

            handleCrop(data);
        }else {
            ((ActivityMain) getActivity()).dialogDismiss();
        }
    } 
}

//启动裁剪Activity
private void beginCrop(Uri source) {
    Uri destination1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/org.chenlijian.test", "test_crop.png"));
    Crop.of(source, destination1).asSquare().start(getActivity());
}

//处理裁剪得到的图片,通过Volley上传到服务器
private void handleCrop(Intent data) {
    Uri uri = Crop.getOutput(data);

    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
        String imagePath = UtilsImageProcess.getPath(bitmap);

        uploadTask = networkModule.arrangeUploadImg("arrangeUploadImg", imagePath);
        uploadTask.setId(0);
        uploadTask.setReceiver(this);
        uploadTask.pullTrigger();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

关于自定义封装Volley接口,上传图片或者文件,我会在下一篇文章中进行分析。

你可能感兴趣的:(Android中获取图片进行裁剪功能的细节分析)