一、拍照+截取
拍照:
mStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);//获取存储器的专门放图片的区域 uri = Uri.fromFile(new File(mStorageDir.getPath()+System.currentTimeMillis()+".png")); //在该区域创建文件,并转换为uri格式 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //将图片处理的数据传递到uri上 intent.putExtra(MediaStore.EXTRA_OUTPUT,uri); //在Dialog中,必须这样使用,才能回调到Activity上 ((Activity)mContext).startActivityForResult(intent,REQUST_PHOTO);
拍照完之后回调
Activity.onActivityResult()
if(requestCode == ImageDialog.REQUST_PHOTO){ //截取图片 第一个参数就是刚才的uri cropImageUri(ImageDialog.uri,800,600,REQUST_CRAP); } 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); }
在从onActivityResult()中保存图片,到地址
else if (requestCode == REQUST_CRAP){ Bitmap bitmap = decodeUriAsBitmap(data.getData()); imageView.setImageBitmap(bitmap); } private Bitmap decodeUriAsBitmap(Uri uri){ Bitmap photo = null; Uri photoUri = uri; if (photoUri != null) { //根据uri地址获取Bitmap photo = BitmapFactory.decodeFile(photoUri.getPath()); } Log.d(TAG,photoUri.getPath()); if (photo == null) { //将图片生成jpeg ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, stream); } return photo; }
二、从相册中选择+截取
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); //表明选择的是image类型 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, uri); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection ((Activity)mContext).startActivityForResult(intent, REQUEST_GALLERY);
之后的步骤跟上面相同