转载声明:Ryan的博客文章欢迎您的转载,但在转载的同时,请注明文章的来源出处,不胜感激! :-) java
http://my.oschina.net/ryanhoo/blog/86865 android
上一篇博客中,咱们学习到了如何使用Android相册截图。在这篇博客中,我将向你们展现如何拍照截图。 git
拍照截图有点儿特殊,要知道,如今的Android智能手机的摄像头都是几百万的像素,拍出来的图片都是很是大的。所以,咱们不能像对待相册截图同样使用Bitmap小图,不管大图小图都统一使用Uri进行操做。 github
1、首先准备好须要使用到的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
2、使用MediaStore.ACTION_IMAGE_CAPTURE能够轻松调用Camera程序进行拍照: spa
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_BIG_PICTURE);//or TAKE_SMALL_PICTURE3、接下来就能够在 onActivityResult中拿到返回的数据(Uri),并将Uri传递给截图的程序。
switch (requestCode) { case TAKE_BIG_PICTURE: Log.d(TAG, "TAKE_BIG_PICTURE: data = " + data);//it seems to be null //TODO sent to crop cropImageUri(imageUri, 800, 400, CROP_BIG_PICTURE); break; case TAKE_SMALL_PICTURE: Log.i(TAG, "TAKE_SMALL_PICTURE: data = " + data); //TODO sent to crop cropImageUri(imageUri, 300, 150, CROP_SMALL_PICTURE); break; default: break; }能够看到,不管是拍大图片仍是小图片,都是使用的Uri,只是尺寸不一样而已。咱们将这个操做封装在一个方法里面。
private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode){ Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); intent.putExtra("return-data", false); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, requestCode); }4、最后一步,咱们已经将数据传入裁剪图片程序,接下来要作的就是处理返回的数据了:
switch (requestCode) { case CROP_BIG_PICTURE://from crop_big_picture Log.d(TAG, "CROP_BIG_PICTURE: data = " + data);//it seems to be null if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri); imageView.setImageBitmap(bitmap); } break; case CROP_SMALL_PICTURE: if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri); imageView.setImageBitmap(bitmap); }else{ Log.e(TAG, "CROP_SMALL_PICTURE: data = " + data); } break; default: break; }
效果图: .net
代码托管于GitHub,会不按期更新:https://github.com/ryanhoo/PhotoCropper code
基础篇: orm