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

标签 android bitmap

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

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

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

我试过这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();
}

第二个:

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

第三:

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

据推测,图像被保存在路径中: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)

最佳答案

在尝试了几件事之后,这就是最终对我有用的东西:

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

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

关于android - 将位图保存到应用程序文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30480906/

相关文章:

android - 如何从 radiogroup 获取值到另一个 Activity ?

android - 如何在我们的android应用程序中使用google授权服务?

android - Onesignal 选择加入弹出窗口 Cordova/Ionic Android 失败

android - 无法从网址下载图片

C++:从位构建迭代器

android - 如何选择最佳图像大小以不超过 VM 预算?

java - 如何检测 FragmentPagerAdapter 显示的第一页或最后一页?

android - 如何处理后退按钮转到特定 fragment ?

Android位图分配怪异

android - 如何使用 Open GL ES 在 Android 中加载巨大的位图?