Jack Jack - 3 years ago 99
Android Question

Image saving to SD card overwriting existing file

I am successfully saving an Image on button click to the SD card in a folder.

The problem I am having is that the image is overwriting the existing image that has previously saved if I save more than 1 file because the file name is the same so it overwrites the exiting image.

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?

Thanks in advance!

Here's what I have so far:

OutputStream output;

Time now = new Time();
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/");

// 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!",
try {

output = new FileOutputStream(file);

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

catch (Exception e) {
// TODO Auto-generated catch block
return false;

Answer Source


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

and get the time at which you're trying to save the file.

Then, attach it to the end of the filename. This way, your files will never have the same name, but will always have the same prefix.

To check if a directory exists,

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

However, devices without SD card won't work as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download