Images are not being saved in my camera app

95 views Asked by At

I'm trying to make an app that detects motion and takes picture when the motion is detected. Its saving the picture when I don't try to save it in the directory(folder). But when I try it with the directory, the picture is not being saved even though the directory is being created successfully. What changes should I make to the following code in order to make it work:

 private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {

        File folder = new File(Environment.getExternalStorageDirectory() +
            File.separator + "XYX APP");
             boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
        if (success) {
        // Do something on success

    } else {
        // Do something else on failure
    }

        File photo = new File(new File(Environment.getExternalStorageDirectory()+"XYZ APP/"), name+ ".jpg");
        if (photo.exists()) {
            photo.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(photo.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Note: The file name is generated in the following instruction:

 String name = "MotDet_"+String.valueOf(System.currentTimeMillis());
            if (bitmap != null) createDirectoryAndSaveFile(name, bitmap);

Update It works with the following code but not with the code above :

    private void save(String name, Bitmap bitmap) {
        File photo = new File(Environment.getExternalStorageDirectory(), name + ".jpg");
        if (photo.exists()) photo.delete();

        try {
            FileOutputStream fos = new FileOutputStream(photo.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
        } catch (java.io.IOException e) {
            Log.e("PictureDemo", "Exception in photoCallback", e);
        }
    }
3

There are 3 answers

5
Jayanth On BEST ANSWER

First of all you missed the FileSeperator before xyz

 File photo = new File(folder.getAbsolutePath()+"/XYZ APP/"+ name+ ".jpg");

And your Function becomes

private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {

File folder = new File(Environment.getExternalStorageDirectory() +
        File.separator + "XYZ APP");//here you have created different name
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success

} else {
    // Do something else on failure
}

File photo = new File(folder.getAbsolutePath(), name+ ".jpg"); 
if (photo.exists()) {
    photo.delete();
}
try {
    FileOutputStream out = new FileOutputStream(photo.getPath());
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}

}

Marshmello comes with RuntimePermissions in order for you to save file in external directory you need to ask permission first, like below code

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}

}

permission result callback

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
      super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
          Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
          //resume tasks needing this permission
      }
   }

before saving call isStoragePermissionsGranted() if it returns true proceed saving file.

2
Hiren Gondaliya On

Try this code :

String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bp, partFilename);

private String currentDateFormat(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
        String  currentTimeStamp = dateFormat.format(new Date());
        return currentTimeStamp;
    }

private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
        File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This code is work for me..Save image to directory.

4
Kishore Jethava On

You have to get permission of external storage at run time in android 6.0 and above to write in SDCard

Read Run time Permission

add in manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

replace your function with below one

private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {

    File folder = new File(Environment.getExternalStorageDirectory() +
            File.separator + "XYZ APP");//here you have created different name
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
    if (success) {
        // Do something on success

    } else {
        // Do something else on failure
    }

    File photo = new File(folder.getAbsolutePath(), name+ ".jpg"); //use path of above created folder
    if (photo.exists()) {
        photo.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(photo.getPath());
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}