Android:将位图保存到外部存储失败

时间:2018-12-26 14:42:05

标签: java android io bitmap android-external-storage

我无法将位图保存到外部存储中。

我也尝试保存一个txt文件,但也无法正常工作。

我的位图代码如下:

fetch(https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photosearth_date=${year}-${month}-${day}&api_key=${API_KEY}`)
.then(res => res.json())
.then(parsedRes => {
    if(year && month && day){
        this.setState({
        sol: parsedRes.photos[0].sol,
        earth_date: parsedRes.photos[0].earth_date,
        img: parsedRes.photos[0].img_src,
        error: ""
        });
    } else {
       this.setState({
       sol: undefined,
       earth_date: undefined,
       img: undefined,
       error: "no pics for this day, try another one"
       }); 
    }
})
.catch(err => {
    console.log(err)
});

这不起作用: 当我运行它时,我得到了(在file.createNewFile();行中):

//filename ends with .png
private void SaveBitmap(Bitmap bitmap, String fileName) {
//Get Pictures folder
    File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//Create new folder and mkdir it if it does not exist.
    File dir = new File(root.getAbsolutePath() + "/ReCorder");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File file = new File (dir, fileName);
    try {                                                             
//Make sure file exists   
        if (!file.exists()) {
             file.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

当我删除文件时。createNewFile();行,我得到:

java.io.IOException: No such file or directory 

我还确保了AndroidManifest.xml中的权限

java.io.FileNotFoundException: /storage/emulated/0/Pictures/ReCorder/test.png

对于调试,我使用Nexus 5X的AndroidStudio集成仿真器。

非常感谢您对我的问题的帮助。预先谢谢你:)

0 个答案:

没有答案