欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > Android >内容正文

Android

Android大图片裁剪终极解决方案

发布时间:2025/3/15 Android 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Android大图片裁剪终极解决方案 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

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

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

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

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

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

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

    一、从相册截大图:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 600); intent.putExtra("outputY", 300); intent.putExtra("scale", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, CHOOSE_BIG_PICTURE);

    二、从相册截小图

?
1 2 3 4 5 6 7 8 9 10 11 12 Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 200); intent.putExtra("outputY", 100); intent.putExtra("scale", true); intent.putExtra("return-data", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, CHOOSE_SMALL_PICTURE);

    三、对应的onActivityResult可以这样处理返回的数据

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 switch (requestCode) { case CHOOSE_BIG_PICTURE:     Log.d(TAG, "CHOOSE_BIG_PICTURE: data = " + data);//it seems to be null     if(imageUri != null){         Bitmap bitmap = decodeUriAsBitmap(imageUri);//decode bitmap         imageView.setImageBitmap(bitmap);     }     break; case CHOOSE_SMALL_PICTURE:     if(data != null){         Bitmap bitmap = data.getParcelableExtra("data");         imageView.setImageBitmap(bitmap);     }else{         Log.e(TAG, "CHOOSE_SMALL_PICTURE: data = " + data);     }     break; default:     break; }
?
1 2 3 4 5 6 7 8 9 10 private Bitmap decodeUriAsBitmap(Uri uri){     Bitmap bitmap = null;     try {         bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));     } catch (FileNotFoundException e) {         e.printStackTrace();         return null;     }     return bitmap; }

    效果图:

大图小图

转载(http://my.oschina.net/ryanhoo/blog/86853)

转载于:https://www.cnblogs.com/cimu/p/4319823.html

总结

以上是生活随笔为你收集整理的Android大图片裁剪终极解决方案的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。