安卓将位图保存在SD卡中



>我使用以下代码将位图保存在SD卡中

String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_images");
        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Image" +".jpg";
       // String imageInSD1 = Environment.getExternalStorageDirectory().getAbsolutePath() +"/saved_images/" +  fname;
        File file = new File (myDir, fname);
       // if (file.exists ()) file.delete ();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap_profile1.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

它工作正常,但问题是我正在循环执行此操作,每 5 秒运行一次图像慢慢缓慢地变魔化. 我只想保存一次图像,如果图像已经在SD卡中,我该如何检查,然后不要保存图像我只有一个名称用于图像图像更改,但其名称保持不变,请告诉我只想保存一张图像一次,如果位图值更改,则图像保存其他图像不保存。

你要找的函数是 file.exists()

创建文件文件后,转到

if(!file.exists())
    try{...
        ....

编辑:完整代码

String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image" +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ())    //  only try to save picture if it doesn't exist already
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap_profile1.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

最新更新