【问题标题】:how to Save bitmap image into my gallery folder in android?如何将位图图像保存到我在 android 中的画廊文件夹中?
【发布时间】:2016-01-05 02:38:55
【问题描述】:

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

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

异常。在执行第一行 try 块后,它会去 catch 文件夹。

请帮忙,我错过了什么????

提前谢谢你...

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

【问题讨论】:

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


    【解决方案1】:

    有几件事可以尝试。

    使用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;
        }
    

    【讨论】:

    • 非常感谢......文件名中的“/”。我用“-”替换了它,它起作用了。但是,根据您的列表,我的文件名中有“:”......到目前为止没有出现问题,但是“/”创建了问题。有什么建议...?
    • : 可能没有造成问题。我想这取决于您对文件名结构等的偏好。如果它不会引起问题,那么也许可以使用
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2014-01-18
    • 2012-01-23
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多