Android大图片裁剪终极解决方案(中:从相册截图)

在这篇博客中,我将向大家展示如何从相册截图。

    上一篇博客中,我就拍照截图这一需求进行了详细的分析,试图让大家了解Android本身的限制,以及我们应当采取的实现方案。

    根据我们的分析与总结,图片的来源有拍照和相册,而可采取的操作有

  • 使用Bitmap并返回数据
  • 使用Uri不返回数据

    前面我们了解到,使用Bitmap有可能会导致图片过大,而不能返回实际大小的图片,我将采用大图Uri,小图Bitmap的数据存储方式。

    我们将要使用到URI来保存拍照后的图片:

1private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file
2Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap

    不难知道,我们从相册选取图片的Action为Intent.ACTION_GET_CONTENT。

    根据我们上一篇博客的分析,我准备好了两个实例的Intent。

    一、从相册截大图:

01Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
02intent.setType("image/*");
03intent.putExtra("crop", "true");
04intent.putExtra("aspectX", 2);
05intent.putExtra("aspectY", 1);
06intent.putExtra("outputX", 600);
07intent.putExtra("outputY", 300);
08intent.putExtra("scale", true);
09intent.putExtra("return-data", false);
10intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
11intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
12intent.putExtra("noFaceDetection", true); // no face detection
13startActivityForResult(intent, CHOOSE_BIG_PICTURE);
    二、从相册截小图
01Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
02intent.setType("image/*");
03intent.putExtra("crop", "true");
04intent.putExtra("aspectX", 2);
05intent.putExtra("aspectY", 1);
06intent.putExtra("outputX", 200);
07intent.putExtra("outputY", 100);
08intent.putExtra("scale", true);
09intent.putExtra("return-data", true);
10intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
11intent.putExtra("noFaceDetection", true); // no face detection
12startActivityForResult(intent, CHOOSE_SMALL_PICTURE);
    三、对应的onActivityResult可以这样处理返回的数据
01switch (requestCode) {
02case CHOOSE_BIG_PICTURE:
03    Log.d(TAG, "CHOOSE_BIG_PICTURE: data = " + data);//it seems to be null
04    if(imageUri != null){
05        Bitmap bitmap = decodeUriAsBitmap(imageUri);//decode bitmap
06        imageView.setImageBitmap(bitmap);
07    }
08    break;
09case CHOOSE_SMALL_PICTURE:
10    if(data != null){
11        Bitmap bitmap = data.getParcelableExtra("data");
12        imageView.setImageBitmap(bitmap);
13    }else{
14        Log.e(TAG, "CHOOSE_SMALL_PICTURE: data = " + data);
15    }
16    break;
17default:
18    break;
19}
01private Bitmap decodeUriAsBitmap(Uri uri){
02    Bitmap bitmap = null;
03    try {
04        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
05    catch (FileNotFoundException e) {
06        e.printStackTrace();
07        return null;
08    }
09    return bitmap;
10}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值