Android - Save images in an specific folder

Here You Go. I tried the above solution they save the image to gallery but the image is not visible , a 404 error is visible on the image , and i figured it out .

public void addToFav(String dirName, Bitmap bitmap) {

    String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
            dirName + System.currentTimeMillis() + ".jpg";
    Log.e("resultpath",resultPath);
    new File(resultPath).getParentFile().mkdir();




    if (Build.VERSION.SDK_INT < 29){
        
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "Photo");
        values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
        values.put("_data", resultPath);

        ContentResolver cr = getContentResolver();
        cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        try {
            OutputStream fileOutputStream = new FileOutputStream(resultPath);
            bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            if(fileOutputStream != null){
                Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e2) {
            e2.printStackTrace();
        }

    }else {

        OutputStream fos = null;
        File file = new File(resultPath);

        final String relativeLocation = Environment.DIRECTORY_PICTURES;
        final ContentValues  contentValues = new ContentValues();

        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation+"/"+dirName);
        contentValues.put(MediaStore.MediaColumns.TITLE, "Photo");
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        contentValues.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis ());
        contentValues.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
        contentValues.put(MediaStore.MediaColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
        contentValues.put(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
        
        final ContentResolver resolver = getContentResolver();
        final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Uri uri = resolver.insert(contentUri, contentValues);

        try {
            fos = resolver.openOutputStream(uri);
            bitmap.compress(CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        if(fos != null){
            Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
        }

    }


}

Go through the following code , its working fine for me.

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {

    File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");

    if (!direct.exists()) {
        File wallpaperDirectory = new File("/sdcard/DirName/");
        wallpaperDirectory.mkdirs();
    }

    File file = new File("/sdcard/DirName/", fileName);
    if (file.exists()) {
        file.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Use Like this. It will work for you.

public void onClick(View v) {
  Intent camera = new Intent(
  android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
  startActivityForResult(camera, 1);
}

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
  super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

  switch(requestCode) {
    case 1:
      if(resultCode == RESULT_OK) {
      Uri selectedImage = imageReturnedIntent.getData();
      String[] filePathColumn = {MediaStore.Images.Media.DATA};

      Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      //file path of captured image
      filePath = cursor.getString(columnIndex);
      //file path of captured image
      File f = new File(filePath);
      filename= f.getName();

      Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
      Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
      cursor.close();

      //Convert file path into bitmap image using below line.
      // yourSelectedImage = BitmapFactory.decodeFile(filePath);
      Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();

      //put bitmapimage in your imageview
      //yourimgView.setImageBitmap(yourSelectedImage);  

      Savefile(filename,filePath);
    }
  }
}

public void Savefile(String name, String path) {
  File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/");
  File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/"+n+".png");

  if(!direct.exists()) {
    direct.mkdir();
  }

  if (!file.exists()) {
    try {
      file.createNewFile();
      FileChannel src = new FileInputStream(path).getChannel();
      FileChannel dst = new FileOutputStream(file).getChannel();
      dst.transferFrom(src, 0, src.size());
      src.close();
      dst.close();

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

Hope this will help you. for reference to use camera intent.


I have used mdDroid's code like this:

public void startCamera() {
    // Create photo
    newPhoto = new Photo();
    newPhoto.setName(App.getPhotoName());

    //Create folder !exist
    String folderPath = Environment.getExternalStorageDirectory() + "/PestControl";
    File folder = new File(folderPath);
    if (!folder.exists()) {
        File wallpaperDirectory = new File(folderPath);
        wallpaperDirectory.mkdirs();
    }
    //create a new file
    newFile = new File(folderPath, newPhoto.getName());

    if (newFile != null) {
        // save image here
        Uri relativePath = Uri.fromFile(newFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, relativePath);
        startActivityForResult(intent, CAMERA_REQUEST);
    }
}