将位图保存到应用程序文件夹

mas*_*mic 2 android bitmap

当我的应用程序第一次启动时,它让用户选择个人资料图片。这可以通过拍摄照片或从图库中选择来完成。

用户获得图片后,必须将其保存在设备的内部存储中,并将在应用程序中用作用户的个人资料图片。

这个过程工作正常,用户获取图片,并在保存之前显示在图像视图中。但是要将图像保存在内部存储器中,我遇到了一些麻烦。我尝试了几种方法来做到这一点,其中大多数似乎都有效。但是当我尝试它们时,图片没有被保存,或者至少我没有找到保存它的文件夹。

我已经尝试过这3种方式:

第一的:

File directory = getDir("profile", Context.MODE_PRIVATE);
File mypath = new File(directory, "thumbnail.png");

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(mypath);
    mybitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.close();
} catch (Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

第二:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mybitmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);

FileOutputStream fos = null;
try {
    fos = openFileOutput("thumbnail.png", Context.MODE_PRIVATE);
    fos.write(bytes.toByteArray());
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

第三:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mybitmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);

File fileWithinMyDir = new File(getFilesDir(), "thumbnail.png");
try {
    FileOutputStream fos = new FileOutputStream(fileWithinMyDir);
    fos.write(bytes.toByteArray());
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

据说,图像保存在路径中:android/data/AppName/app_data/但那里没有创建文件夹。无论如何,我查看了其他文件夹,但什么也没有。

编辑-

在第一种方法中,我已经看到抛出异常:

E/SAVE_IMAGE? /data/data/com.example.myapp/app_profile/thumbnail.png: open failed: EISDIR (Is a directory)
java.io.FileNotFoundException: /data/data/com.example.myapp/app_profile/thumbnail.png: open failed: EISDIR (Is a directory)
Caused by: libcore.io.ErrnoException: open failed: EISDIR (Is a directory)
Run Code Online (Sandbox Code Playgroud)

mas*_*mic 6

在尝试了几件事之后,这最终对我有用:

ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("profile", Context.MODE_PRIVATE);
if (!directory.exists()) {
    directory.mkdir();
}
File mypath = new File(directory, "thumbnail.png");

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(mypath);
    resizedbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.close();
} catch (Exception e) {
    Log.e("SAVE_IMAGE", e.getMessage(), e);
}
Run Code Online (Sandbox Code Playgroud)

基本上事情是检查目录(而不是文件)是否存在,如果不存在,则使用 mkdir() 创建它。

  • `Context#getDir()` 如果文件夹不存在,则创建该文件夹,因此调用 `mkdir()` 是多余的(来源:Context.java 文档) (2认同)