【问题标题】:Reading a bitmap from sdcard从 sdcard 读取位图
【发布时间】:2017-05-09 14:42:18
【问题描述】:

我通过裁剪意图在 SD 卡中保存了一个位图文件,我想在另一个活动中读取它。但是,我不断收到以下运行时错误:无法解码流:java.io.FileNotFoundException:文件:/sdcard/oc.jpg:打开失败:ENOENT(没有这样的文件或目录) E/ReadFile: 位图必须为非空

Uri uri=Uri.parse("file:///sdcard/oc.jpg");
//save output image in uri
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 

在另一个活动中读取相同的文件:

Bitmap image4 = BitmapFactory.decodeFile("file:///sdcard/oc.jpg");

我尝试了this solution,但没有成功,并且出现了同样的运行时错误。

【问题讨论】:

  • “我通过裁剪意图在 SD 卡中保存了一个位图文件” -- Android does not have a CROP Intent。 “无法解码流:java.io.FileNotFoundException: file:/sdcard/oc.jpg”——不要硬编码路径(使用方法,如Environment.getExternalStorageDirectory()),并确保您拥有适当的权限(包括运行时权限)。
  • 我试过 String imageInSD =Environment.getExternalStorageDirectory().getAbsolutePath() +"oc.jpg"; image4 = BitmapFactory.decodeFile(imageInSD);但我仍然无法读取位图,并且我包含了运行时权限
  • ....getAbsolutePath() +"oc.jpg" 那应该是.getAbsolutePath() +"/oc.jpg"
  • decodeFile("file:///sdcard/oc.jpg"); 如果你想在测试期间使用硬编码路径,那应该是decodeFile("/sdcard/oc.jpg");
  • @greenapp 是的,我忘记了 /,但即使使用它也不起作用。

标签: android bitmap sd-card


【解决方案1】:

您需要写入外部存储,确保您添加了权限:

<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...

检查外部存储是否可用于读写

    public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

使用公共目录的根目录,而不是使用 Android 的根目录。

如果要将公共文件保存在外部存储上,请使用 getExternalStoragePublicDirectory()

    public File getAlbumStorageDir(String albumName) {
    // Get the directory for the user's public pictures directory. 
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

如果您想保存应用程序私有的文件,请使用 getExternalFilesDir()

    public File getAlbumStorageDir(Context context, String albumName) {
    // Get the directory for the app's private pictures directory. 
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_DCIM), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

我忘了说:

decodeFile 期望路径

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    相关资源
    最近更新 更多