android 4.3相册选取截图“无法加载图片”问题

来源:互联网 发布:10月经济数据 统计局 编辑:程序博客网 时间:2024/06/15 08:11

刚刚开始写博文,难免有疏忽的地方,见谅。废话不多说了,这两天在做项目的时候,发现4.3版本的系统在相册选择图片截取的时候,总是会出现无法加载图片。翻阅了一些资料,在Android 4.4之前,调用系统图库拿到图片的Uri和4.4或以上的Uri是有很大区别,单单使用Intent.ACTION_GET_CONTENT在4.4或以上的版本是无法解析拿到的Uri的。因此,在调用图库之前,版本的英文Build.VERSION_CODES.KITKAT或以上的版本,官方建议用ACTION_OPEN_DOCUMENT。下面直接上代码:
//选取相册 用比较一下当前系统版本

private void getAlbum() {
String intentactiong = “”;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {//4.4版本前
intentactiong = Intent.ACTION_PICK;
} else {//4.4版本后
intentactiong = Intent.ACTION_GET_CONTENT;
}
Intent openAlbumIntent = new Intent(intentactiong);
openAlbumIntent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, “image/*”);
startActivityForResult(openAlbumIntent, FLAG_SELECT_PHOE);
}
下面是截取图片方法两个版本的图片选取路径不同,所以为了适配不同版本系统,这里做了主动存储图片。
// 截取图片
public void cropImage(Uri uri, int outputX, int outputY, int requestCode) {
if (uri != null) {
Intent intent = new Intent(“com.android.camera.action.CROP”);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {//4.4版本前
//以当前时间为存储名字
String fileName = String.valueOf(System.currentTimeMillis()) + “.png”;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(“tempName”, fileName);
editor.commit();
//生成存储Uri路径
Uri imageUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), fileName));
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
}
intent.setDataAndType(uri, “image/*”);
intent.putExtra(“crop”, “true”);
intent.putExtra(“aspectX”, 1);
intent.putExtra(“aspectY”, 1);
intent.putExtra(“outputX”, outputX);
intent.putExtra(“outputY”, outputY);
intent.putExtra(“outputFormat”, “PNG”);
intent.putExtra(“noFaceDetection”, true);
intent.putExtra(“return-data”, true);
startActivityForResult(intent, requestCode);
}
}
在onactivityresult回调方法中
onActivityResult
Uri uri = null;
if (data != null) {
uri = data.getData();
System.out.println(“Data”);
} else {
System.out.println(“File”);
String fileName = getSharedPreferences(“temp”,
Context.MODE_PRIVATE).getString(“tempName”,
“”);
uri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), fileName));
}
try {
Bitmap bitmaps = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), uri);
img_1.setImageBitmap(bitmaps);

} catch (IOException e) {    e.printStackTrace();}cropImage(uri, PHOTOSIZE, PHOTOSIZE, FLAG_CROP_PHONE);

另附上源码 https://github.com/longyuan02/Interceptpictures

原创粉丝点击