Android将位图写入sdcard

时间:2011-08-11 06:30:14

标签: java android bitmap sd-card

我正在尝试将一个位图写入android上的sdcard,我收到的错误信息为 /mnt/sdcard/PhysicsSketchpad/sketchpad145.png (No such file or directory).
我在清单中声明了android.permission.WRITE_EXTERNAL_STORAGE权限,这是我的代码:

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                        "/PhysicsSketchpad/";
File dir = new File(file_path);
dir.mkdirs();
File file = new File(dir, "sketchpad" + pad.t_id + ".png");
FileOutputStream fOut = new FileOutputStream(file);

bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();

发生了什么事?

更新

好像当我尝试写入现有目录时,我收到了一个权限被拒绝的错误,

08-11 09:55:23.796: WARN/Physics Sketchpad(8881): Error when saving: IOException /mnt/sdcard/download/sketchpad54.png (Permission denied)

当我尝试保存在新目录中时,我得到一个没有这样的文件或目录错误,08-11 09:59:20.175: WARN/Physics Sketchpad(9040): Error when saving: IOException /mnt/sdcard/PhysicsSketchpad/sketchpad55.png (No such file or directory)

此外,File.mkdirs()根据成功与否返回布尔值,返回false。

3 个答案:

答案 0 :(得分:4)

试试这段代码。

  String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                            "/PhysicsSketchpad";
    File dir = new File(file_path);
if(!dir.exists)
    dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);

    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();

答案 1 :(得分:3)

试试这段代码。这对我有用。

public void saveBitmap(Bitmap bm)
{
    try
    {
        String mBaseFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/";
        String mFilePath = mBaseFolderPath + "abcd.jpg";

        FileOutputStream stream = new FileOutputStream(mFilePath);
        bm.compress(CompressFormat.JPEG, 100, stream);
        stream.flush();
        stream.close();
    }
    catch(Exception e)
    {
        Log.e("Could not save", e.toString());
    }
}

词shash

答案 2 :(得分:0)

你得到绝对路径检查错误你得到的路径

/mnt/sdcard/AppName/appname145.png

然后设置

Environment.getExternalStorageDirectory().getAbsolutePath() + 
                        "/PhysicsSketchpad/";

其中“PhysicsSketchpad”目录没有进入上面的路径

试试这个

Environment.getExternalStorageDirectory().toString()+ "/PhysicsSketchpad/";