简体   繁体   中英

android save bitmap in sd card

i save the bitmap in sd card with the following code

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

its working fine but issue is this i am doing this in loop which run every 5 sec the image slowly slowly demage . i want to save the image only one time how can i check this if image is already in sd card then do not save the image i have only one name for image image change but its name remain same please tell i want to save the one image for only one time if bitmap value change then image save othervise image not save.

The function you're looking for is file.exists()

After creating your File file, go

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

Edit: Full code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM