BitmapFactory.decodeStream返回空值:Android
我在第二个类(Class2)中有一个方法,在这里我从Class1传入context和uri的值。第二个类(Class2)是一个将过滤器应用于使用Class1中的相机拍摄的图像的类。类2中的方法类似于BitmapFactory.decodeStream返回空值:Android,android,bitmap,camera,Android,Bitmap,Camera,我在第二个类(Class2)中有一个方法,在这里我从Class1传入context和uri的值。第二个类(Class2)是一个将过滤器应用于使用Class1中的相机拍摄的图像的类。类2中的方法类似于 public void prepareImage(Context context, Uri uri) { // BitmapFactory options Options options = new Options(); options.inSampleSize = 2;
public void prepareImage(Context context, Uri uri) {
// BitmapFactory options
Options options = new Options();
options.inSampleSize = 2;
String path = uri.toString();
File file = new File(path);
FileInputStream fis = null; //initialize
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap img = BitmapFactory.decodeStream(fis);
Log.i(TAG, "Bitmap img: " + img);
//more code below, but above this comment is where the issue is
}
我注意到FileInputStream返回null,因此BitmapFactory.decodeStream没有解码任何内容。有两件事我认为是问题,但我不确定如何解决它们。首先,我想知道我是否接收到FileInputStream的null,因为我使用的路径是由uri.toString()形成的。或者这有关系吗?字符串路径值正确
第二个问题是,如果我的手机与电脑相连,在使用我的应用程序拍摄图像后,图像文件似乎在我从电脑上拔下设备后才会注册。只有在我从计算机上拔下设备后,我的所有图像才会显示在gallery文件夹中。所以我怀疑文件找不到了!logcat提供了这方面的证据
无论如何,我不知道如何避免这场冲突。也许我需要用另一种方式保存图像。下面是我如何在Class1中保存图像
File imgFileDir = getDir();
if (!imgFileDir.exists() && !imgFileDir.mkdirs()) {
Log.e(TAG, "Directory does not exist");
}
//Locale.US to get local formatting
SimpleDateFormat timeFormat = new SimpleDateFormat("hhmmss", Locale.US);
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.US);
String time = timeFormat.format(new Date());
String date = dateFormat.format(new Date());
String photoFile = date + "_nameofapp_" + time + ".jpg";
String filename = imgFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(arg0);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e(TAG, "Image could not be saved");
e.printStackTrace();
}
我还使用助手方法
private File getDir() {
File sdDir = Environment.
getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "NameOfApp");
}
最后,我试着将应用程序与我的计算机分离运行,看看它是否能工作,但它不能工作。行为是一样的,我拍摄的图像不会显示在多媒体资料中,直到我将设备重新插入计算机,然后我拍摄的所有图像都会显示在多媒体资料中。为什么?
根据请求,我将从Class1传递URI,并执行以下操作
Class2 classTwo = new Class2();
classTwo.prepareImage(this, uri);
只需将此移动到一个答案,以便每个人都能看到: 看起来您的文件Uri中有一个额外的
/
file:/storage/emulated/0 ...
对
/file:/storage/emulated/0 ... (from the exception message)
:)你能告诉我你在哪里调用
prepareImage()
以及你传递给它的Uri
吗?嘿,贾斯汀,我更新了我的帖子。你的问题的答案在最后。Uri是公共的和静态的,我实际上已经尝试过用setter/getter编写这段代码,以双重确认Uri是否到达Class2。它就在那里,但Uri是什么?在您的日志中,它看起来像是一个额外的/
<代码>文件:/storage/emulated/0…与/file:/storage/emulated/0…
(来自异常消息)。贾斯汀,你是天才。这就是问题所在。修复方法不是使用URI.fromFile()获取URI,而是使用URI.parse()。两者的区别在于fromFile()添加了一个额外的/。谢谢你,伙计,现在这个很好用!如果你能给出一个答案,我也会接受。完成了,完成了:)很高兴我能帮上忙!有时,当您整天都在看代码时,这些细节会变得模糊(我自己也经历了太多次)。