如何将位图保存到android中的应用程序文件夹中

问题描述 投票:0回答:3

我有一个位图,我想将其保存到应用程序文件夹中。我尝试使用以下代码:

 ContextWrapper contextWrapper = new ContextWrapper(context.getApplicationContext());
 File directory = contextWrapper.getDir("tabs", Context.MODE_PRIVATE);
 if (!directory.exists())
     directory.mkdir();
     String fname = "Image.jpg";
     File file = new File(directory, fname);
     FileOutputStream fos = null;
     try {
         fos = new FileOutputStream(file);
         bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
         fos.close();
     } catch (Exception e) {
            Log.e("SAVE_IMAGE", e.getMessage(), e);
     }

现在,我有两个问题。

  1. 为什么显示此警告以及如何解决它?

'File.mkdir()的结果被忽略

  1. 目录“ app_tabs”已在应用程序文件夹中创建,但未保存位图,并且该文件夹中没有照片。如何保存该位图?

ScreenShot

java android android-file
3个回答
1
投票

您可以执行此操作:

try {
     FileOutputStream fileOutputStream = context.openFileOutput("Your File Name", Context.MODE_PRIVATE);
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
     fileOutputStream.close();
 } catch (Exception e) {
     e.printStackTrace();
 }

它将位图保存在应用程序文件夹的“文件”目录中。


0
投票
 String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/tabs";
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();

        File futureStudioIconFile = new File(path, "Image.jpg);
        if (futureStudioIconFile.exists())
            futureStudioIconFile.delete();
        futureStudioIconFile.createNewFile();

尝试这个,希望对您有帮助


0
投票

技术上您的代码是正确的,而且我在自己的设备上尝试过的所有代码都是正确的。

所以我怀疑您找到了其他路径,或者,如果您使用Android Studio检查文件,则需要单击“同步”菜单。


0
投票

这是我的答案

  1. [Result of 'File.mkdir()' is ignored:因为mkdir()返回一个布尔值,如果创建了文件夹,则返回true,否则返回false。

  2. 这是我保存位图的方式

        File storageDir = getFilesDir();

        File filePath = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );


        try (FileOutputStream out = new FileOutputStream(filePath)) {
            capturedImg.compress(Bitmap.CompressFormat.JPEG, quality, out);
        } catch (IOException e) {
            e.printStackTrace();
        }

或者,如果您只想以原始分辨率保存位图,则>]

    public static void copy(Uri uri, File dst, Context context) {
        try (InputStream in = context.getContentResolver().openInputStream(uri);
             OutputStream out = new FileOutputStream(dst)) {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.