我想要手动添加本地的相册中的图片到imageview中,但是选择的图片都会变为0kb导致无法加载。
public void onClick(View v) {
File outputImage = new File(Environment.getExternalStorageDirectory(),
"output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
intent.putExtra("crop", true);
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
onActivityResult部分代码
case CROP_PHOTO:
if(data==null){
Log.e();
}
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
我的手机是Android4.4的测试下来都不行相似的问题http://.com/q/1010000002513172
但是我根据下面的方法并没有解决问题,希望帮忙解答一下,问题到底出在了哪里,google的解决方案都不适用,都是检验data!=null
但是对出现了null却没有提及解决方案。
我没有4.4的系统,在5.1上测试你的代码,成功运行。
E/CrimeFragment: Result: take photo data: Intent { dat=file:///storage/emulated/0/output_image.jpg (has extras) }, ImageUri: file:///storage/emulated/0/output_image.jpg
没加权限WRITE_EXTERNAL_STORAGE
时,data依然不为null,只是抛出如下error:
java.io.FileNotFoundException: /storage/emulated/0/output_image.jpg: open failed: EACCES (Permission denied)
目前只能帮你排除到这儿了。没有4.4无法确认你的问题原因~
是这里的问题imageuri
的问题,作者为了配合拍照的功能在裁减的部分使用了
case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
但是从图库中选取的时候这里的imageuri对应的只是一个0kb的图片,如果只是用data.getData()就不会出现问题,我的表达不好导致错误引导了许多答主,对不起(-。-;)
你start的时候requestCode是TAKE_PHOTO,处理result的case却是CROP_PHOTO,你的TAKE_PHOTO和CROP_PHOTO是同一个值吗?亲测在requestCode和result case相同的情况下,4.4上并未出现data为null的情况
其实应该和手机品牌有关,你可以尝试不同intent去获取相册的内容,因为很多手机修改了默认相册程序,其实有时候调用相册未必能获取正确的内容,系统应用应该有两种(图库,相册),你可以测试下是否是因为调用系统应用产生的问题。
Intent galleryIntent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
我用的是这个,可以参考下,同样系统的截图应用也是,最好分别测试下,同样的问题我遇到过,应该是手机产商定制导致的问题。
检查下是否有媒体访问权限