Android 使用文件路径从库中检索图像
使用以下代码将图像保存到文件系统并将其路径保存到db中后,我希望使用文件路径检索同一张照片,而无需启动gallery供用户选择。我发现的所有建议都需要使用启动图库的意图Android 使用文件路径从库中检索图像,android,Android,使用以下代码将图像保存到文件系统并将其路径保存到db中后,我希望使用文件路径检索同一张照片,而无需启动gallery供用户选择。我发现的所有建议都需要使用启动图库的意图 private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) { File direct = new File(Environment.getExternalStorageDirectory() + "/DirName"); if (
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
调用此类型的函数,可以返回文件路径,使用此文件路径,可以在ImageView上显示图像
private String createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
如果已经有路径,请尝试:
File imgFile = new File("/sdcard/Images/sample_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}