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

声明:Ryan的博客文章欢迎您的转载,但在转载的同时,请注明文章的来源出处,不胜感激! :-) 
java

http://my.oschina.net/ryanhoo/blog/86853 spa


    在这篇博客中,我将向你们展现如何从相册截图。 .net

    上一篇博客中,我就拍照截图这一需求进行了详细的分析,试图让你们了解Android自己的限制,以及咱们应当采起的实现方案。 code

    根据咱们的分析与总结,图片的来源有拍照和相册,而可采起的操做有 orm

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

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

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

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。 ci

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

    1、从相册截大图: 博客

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);
    2、从相册截小图
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);
    3、对应的onActivityResult能够这样处理返回的数据
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;
}
private Bitmap decodeUriAsBitmap(Uri uri){
	Bitmap bitmap = null;
	try {
		bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
	} catch (FileNotFoundException e) {
		e.printStackTrace();
		return null;
	}
	return bitmap;
}

    效果图:

大图 小图



基础篇:

【译】如何使用Android MediaStore裁剪大图片

上篇:

Android大图片裁剪终极解决方案(上:原理分析)

下篇:

Android大图片裁剪终极解决方案(下:拍照截图)

相关文章
相关标签/搜索