1

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" />

4 Answers4

1

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:

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Ok, i go try and i back with feedback – Matheus Saviczki Feb 26 '17 at 20:30
  • I test with runtimer request and permissions, and it create the folder, i cheched the folder with a scan, more its not show on my gallery when i save the image – Matheus Saviczki Feb 26 '17 at 21:15
  • @MatheusSaviczki: "i cheched the folder with a scan" -- you do not scan the folder. You scan the JPEG file, once the JPEG file has been created. You also may need to refresh or exit and restart the gallery app, as it may not detect newly-added images while it is running. – CommonsWare Feb 26 '17 at 21:16
  • I closed it and checked it but it is not in the gallery. – Matheus Saviczki Feb 26 '17 at 21:18
  • i used this to scan: private void scanFile(String path) { MediaScannerConnection.scanFile(MainActivity.this, new String[] { path }, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { Log.i("TAG", "Finished scanning " + path); } }); } more its not still show on my gallery – Matheus Saviczki Feb 26 '17 at 21:39
  • @MatheusSaviczki: Perhaps there is an issue with your gallery app. Perhaps you are not passing in the correct value for `path`. – CommonsWare Feb 26 '17 at 21:41
  • I thought of that, could you tell me a standard path for most devices? – Matheus Saviczki Feb 26 '17 at 21:43
  • @MatheusSaviczki: I do not know what you mean by "a standard path", sorry. I would recommend that you use `Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)` to get to the `DCIM/` folder. – CommonsWare Feb 26 '17 at 21:46
  • its created the folder hehe TY =), more its droping on my Catch(FileNotFoundExcption) and its my error: FileNotFoundException: /storage/emulated/0/MEUCAMINHO: open failed: EISDIR (Is a directory) – Matheus Saviczki Feb 26 '17 at 21:59
  • I was able to solve my problem guys thanks for everything – Matheus Saviczki Feb 26 '17 at 22:48
0

You may use the below code for asking runtime storage permission:

final int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
                                if (!checkIfAlreadyhavePermission()) {                                                              

ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                    } else {
                                       TrySaveMediaStore() ;
                                    }

checkIfAlreadyhavePermission() method:

private boolean checkIfAlreadyhavePermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

Add onRequestPermission():

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    TrySaveMediaStore();

                } else {
                    Toast.makeText(this, "Please give your permission.", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }

After creating the file scan MediaStore:

public void scanFile(Context c, File file, String mimeType) {
    MediaScannerConnection
        .scanFile(c, new String[] {file.getAbsolutePath()},
                  new String[] {mimeType}, null);
}
tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
  • I test with runtimer request and permissions, and it create the folder, i cheched the folder with a scan, more its not show on my gallery when i save the image – Matheus Saviczki Feb 26 '17 at 21:14
  • Did you scan your Mediastore as @CommonsWare suggested? Unless you do this gallery will not able to know your newly created file's directory. I've added this to my answer. – tahsinRupam Feb 26 '17 at 21:20
  • i used this to scan: private void scanFile(String path) { MediaScannerConnection.scanFile(MainActivity.this, new String[] { path }, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { Log.i("TAG", "Finished scanning " + path); } }); } more its not still show on my gallery – Matheus Saviczki Feb 26 '17 at 21:40
  • I was able to solve my problem guys thanks for everything – Matheus Saviczki Feb 26 '17 at 22:48
0

i think a had the same problem, actually the image do insert just fine in the memory, but when i tried to watch it didn't show as i expected, i solved it refreshing the gallery with the scanner class, used this code:

MediaScannerConnection.scanFile(this,
        new String[] { file.toString() }, null,
        new MediaScannerConnection.OnScanCompletedListener() {
    public void onScanCompleted(String path, Uri uri) {
        Log.i("ExternalStorage", "Scanned " + path + ":");
        Log.i("ExternalStorage", "-> uri=" + uri);
    }
});

See this link for more info: How can I refresh the Gallery after I inserted an Image in android?

Community
  • 1
  • 1
karique
  • 533
  • 6
  • 17
0

Yes, the problem is the media scanner. Yo can simply check the file using a terminal (download the app if you don't have it) and go manually to the directory. I had the same problem, but at least I know the file is there.