使用filepath从库中检索图像

时间:2015-11-26 04:10:37

标签: android

使用以下代码将图像保存到文件系统并在db中保存其路径,我想使用文件路径检索相同的照片而不启动图库供用户选择它。我发现的所有建议都需要使用启动图库的意图。

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();
    }

}

2 个答案:

答案 0 :(得分:0)

调用此类函数,可以返回文件路径并使用此文件路径,可以在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();

}

答案 1 :(得分:0)

如果您已经有路径,请尝试:

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);

}