Search code examples
javaandroidtoast

Android not create a folder in gallery


I'm trying to save an image on JPG format on a specific folder from my gallery. But my code is not creating a directory, whenever i create a Toast it return for me /storage/emulated/0/DCIM/MyFodler,but when will i open the gallery, this foder not exist. I'm building the application direct of my devide with Android Marshmallow 6.0.

Code to create Bitmap:

    private Bitmap getToBitmap(ImageView view, int Width, int Heigth){
    Bitmap bitmap = Bitmap.createBitmap(Width,Heigth, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

Code to try save the image on gallery:

    private void TrySaveMediaStore(){
    String path = Environment.getExternalStorageDirectory().toString();
    OutputStream FileOut = null;
    File file = new File(path,"DCIM/MyFolder");
    file.mkdirs();
    Toast.makeText(getApplicationContext(),file.getAbsolutePath(),Toast.LENGTH_SHORT).show();

    try{
        FileOut = new FileOutputStream(file);
        FileOut.flush();
        FileOut.close();
        Bitmap bitmap = getToBitmap(img,img.getMaxWidth(),img.getMaxHeight());
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,FileOut);
        MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
        Toast.makeText(this,file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
    }catch (FileNotFoundException e){
        return;
    }catch (IOException e){
        e.printStackTrace();
    }

}

Androidmanifest permissions:

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

Solution

  • DCIM/MyFolder is a directory. You create this as a directory using mkdirs().

    You cannot then try using DCIM/MyFolder as a filename for saving a JPEG. You need to create a file inside the directory.

    So, instead of:

    FileOut = new FileOutputStream(file);
    

    use something like:

    File theActualImageFile=new File(file, "something.jpeg");
    FileOut = new FileOutputStream(theActualImageFile);
    

    Also: