本篇一共解决了7.0拍照遇到的三个问题:
- 调用系统相机返回data为null
- 相机拍照完成后,调系统裁剪会吐司提示“无法加载图片”
- 裁剪完成后返回data为null
一、在清单文件中加入provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.powerpeak.zns.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
二、在res下新建文件夹xml以及文件provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--"."表示所有路径-->
<external-path name="external_files" path="."/>
</paths>
三、代码中应用
相机拍照等功能在另一篇博客有提到,这里没有重复写,只把两篇博客不一样的地方提了出来。
//获取系统版本号
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//图片路径?照相后图片要存储的位置
try {
File imageFile = createImageFile();
picPath = imageFile.getPath();
photouri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", imageFile);
} catch (IOException e) {
e.printStackTrace();
}
//将相机拍照的图片存入指定uri
getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, photouri);
// getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
//获取图片文件名以及裁剪后的文件名
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//判断路径是否存在,不存在则创建
if(!storageDir.exists()){
storageDir.mkdirs();
}
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
String imageCropFileName="CROP_"+timeStamp+"_";
Crop_path=File.createTempFile(imageCropFileName,".jpg",storageDir);
return image;
}
private File Crop_path;
/**
* 裁剪
*
* @param
*/
protected void cropPic(File file) {
if (!file.exists()) {
Toast.makeText(this, "图片不存在", Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent();
intent.setAction("com.android.camera.action.CROP");
//不写这两步,拍照完有可能会报“无法加载图片”
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if(currentapiVersion<24){
intent.setDataAndType(Uri.fromFile(file), "image/*");// mUri是已经选择的图片Uri
}
else{
intent.setDataAndType(FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file), "image/*");// mUri是已经选择的图片Uri
}
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);// 裁剪框比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 150);// 输出图片大小
intent.putExtra("outputY", 150);
//在华为手机上,7.0以后的系统裁剪完返回的data为null,裁剪完图片存放的地址只能这么写,否则会报错
if(currentapiVersion>=24){
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile( Crop_path));
}
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_CROP);
}