1

我成功地将按钮上的图像保存到文件夹中的 SD 卡。

我遇到的问题是,如果我保存超过 1 个文件,图像将覆盖先前保存的现有图像,因为文件名相同,因此它会覆盖现有图像。

有什么办法可以做到,所以当图像保存时,它每次都用不同的名称保存,这样它就不会被覆盖?

提前致谢!

这是我到目前为止所拥有的:

OutputStream output;

        Time now = new Time();
        now.setToNow();
        String time = now.toString();

        // Retrieve the image from the res folder
        BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
        Bitmap bitmap1 = drawable.getBitmap();

        // Find the SD Card path
        File filepath = Environment.getExternalStorageDirectory();

        // Create a new folder in SD Card
        File dir = new File(filepath.getAbsolutePath()
                + "/Wallpapers/");
        dir.mkdirs();

        // Create a name for the saved image
        File file = new File(dir, "Wallpaper"+ time );

        // Show a toast message on successful save
        Toast.makeText(getActivity(), "Wallpaper saved with success!",
                Toast.LENGTH_LONG).show();
        try {

            output = new FileOutputStream(file);

            // Compress into png format image from 0% - 100%
            bitmap1.compress(Bitmap.CompressFormat.PNG, 100, output);
            output.flush();
            output.close();
        }

        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
4

2 回答 2

1

采用:

Time now = new Time();
now.setToNow();
String time = now.toString();

并获取您尝试保存文件的时间。

然后,将其附加到文件名的末尾。这样,您的文件将永远不会具有相同的名称,但将始终具有相同的前缀。

要检查目录是否存在,

File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
if(dir.exists() && dir.isDirectory()) {
    // do something here
}

但是,没有 SD 卡的设备将无法按预期工作。

于 2013-10-16T17:43:32.460 回答
1
Would there be any way I would be able to make it so when the image saves, 
it saves with a different name each time so it doesn't overwrite?

是的,在使用File.exists(). 这样做:

   File file = new File(dir, "Wallpaper.jpg");
   if(file.exists()){
        // assign different name to file
    }
   else{
         // file not present with same name
    }
于 2013-10-16T17:44:12.810 回答