如何将位图图像保存到我在android中的gallery文件夹中?

时间:2016-01-04 18:21:26

标签: android android-intent android-activity bitmapimage android-bitmap

这是我保存图片的代码。我已经提到了文件夹名称,我也想在其中保存图像,因此它将在图库中,但它不起作用我的图像被保存在默认的“图片”文件夹中。当我调试时,显示

java.io.FileNotFoundException:/storage/emulated/0/MyFolderName/aaa-13:15:44/1-4-2016.jpg:open failed:ENOENT(没有这样的文件或目录)

异常。它在执行try块的第一行后立即捕获文件夹。

请帮助,我缺少什么????

提前谢谢你......

    public void saveImage(Bitmap bitmap){
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/MyFolderName"); //my folder name where I want to save.
    String receiverN = receiverName.getText().toString();

    myDir.mkdirs();
    Calendar c = Calendar.getInstance();
    String month, day, year, hour, minute, second;
    month = ""+ (c.get(Calendar.MONTH)+1);
    day = "" + c.get(Calendar.DAY_OF_MONTH);
    year = "" + c.get(Calendar.YEAR);
    hour = ""+c.get(Calendar.HOUR_OF_DAY);
    minute = "" + c.get(Calendar.MINUTE);
    int seconds = c.get(Calendar.SECOND);
    if (seconds<10) second = "0"+ seconds;
    else second = ""+seconds;

    String fname = receiverN + "-" + hour + ":" + minute + ":" + second + "/"  + month + "-" + day + "-" + year +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file); //from here it goes to catch block
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        String[] paths = {file.toString()};
        String[] mimeTypes = {"/image/jpeg"};
        MediaScannerConnection.scanFile(this, paths, mimeTypes, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

要尝试的一些事情。

File.separator字符使用/

不是将外部存储目录转换为字符串,而是在File构造函数中使用它。

File myDir = new File( Environment.getExternalStorageDirectory(),File.separator+"MyFolderName");

您的实际文件名称中包含/。我会使用以下内容删除该字符以及可能导致文件名出现问题的任何其他字符。

public static String encodeString(String string) {

        if (string != null) {
            string = string.replace("/","-");
            string = string.replace(" ","_");
            string = string.replace(":", "-");
            string = string.replace("&", "-");
        }
        return string;
    }