我全部,我已将我的图像保存到外部目录,如下所示:
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Images");
imagesFolder.mkdirs();
image = new File(imagesFolder.getPath(), "MyImage_" + timeStamp + ".jpg");
fileUri = Uri.fromFile(image);
然后将图像保存在数据库(SQLite)中,如下所示:
contentValues.put(LocationsDB.FIELD_FILEPATH, fileUri.toString());
将图像加载到imageView:
String theimage = null;
.....
theimage = arg1.getString(arg1.getColumnIndex(LocationsDB.FIELD_FILEPATH));
.....
final Bitmap myImage = BitmapFactory.decodeFile(theimage);
ImageView image = (ImageView) findViewById(R.id.PicView);
image.setImageBitmap(myImage);
但是在运行应用程序时出现此错误:
01-10 12:12:26.943: E/BitmapFactory(30607): Unable to decode stream: java.io.FileNotFoundException: /file:/storage/emulated/0/Images/MyImage_20150110_121217.jpg: open failed: ENOENT (No such file or directory)
我在这里做错了什么?我以为这会得到图像并显示图像?
答案 0 :(得分:1)
首先确保您的图片存储在Image
文件夹
但您的问题是fromFile()
方法,它会将file://
添加到图片的绝对路径,因此BitmapFactory
无法找到您的图片并抛出java.io.FileNotFoundException
。< / p>
您的图片地址是
file:///storage/emulated/0/Images/MyImage_1234.jpg
而不是
/storage/emulated/0/Images/MyImage_1234.jpg
尝试更改
contentValues.put(LocationsDB.FIELD_FILEPATH, fileUri.toString());
到
contentValues.put(LocationsDB.FIELD_FILEPATH, image.getAbsolutePath());
答案 1 :(得分:0)
问题是new File()
,没有创建文件。它会创建一个指向该位置的指针。
您需要使用OutputStream来保存该文件:
// Open file
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Images");
imagesFolder.mkdirs();
File image = new File(imagesFolder.getPath(), "MyImage_.jpg");
// Create it if it doesn't exist
if (!image.exists()) {
try {
// Create file
FileOutputStream outputStream = new FileOutputStream(image);
outputStream.write("Hello".getBytes());
outputStream.close();
// Save ABSOLUTE_PATH to DB
contentValues.put(LocationsDB.FIELD_FILEPATH, image.getAbsolutePath());
...
} catch (IOException e) {
e.printStackTrace();
}
}
然后从DB获取路径并使用
String absPath = arg1.getString(arg1.getColumnIndex(LocationsDB.FIELD_FILEPATH));
final Bitmap myImage = BitmapFactory.decodeFile(absPath);