1

I modified some code to write a Bitmap to internal storage (Android) that previously wrote to external storage successfully. But compress() is now returning false. Unfortunately the docs do not describe conditions that are likely to cause this, and of course since no exception being thrown there's no help there.

Below is my code.

// Only change made was to the line immediately below, now commented out 
// File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/AIL_SCANS"); //Creates app specific folder

        File directory = contextIn.getDir("my_pics", Context.MODE_PRIVATE);
        if (!directory.exists())
            directory.mkdirs();

        File file = new File(directory, sFilenameIn + ".jpg");

        FileOutputStream os = new FileOutputStream(file);
        if (!imageIn.compress(Bitmap.CompressFormat.JPEG, 100, os))
            Log.e("Error", "     compress() failed (returned false)");

        os.flush();
        os.getFD().sync();
        os.close();
        Log.e("Success", "     Profit!!");

My code created the Bitmap as ARGB_8888 (see below) so a couple of other Stack Overflow posts reporting a similar failure do not seem to apply here.

bmp = Bitmap.createBitmap(arrPixels, widh, height, Bitmap.Config.ARGB_8888);

An example of some code that apparently has worked well for a large number of Stack Overflow users looks almost exactly like mine. Saving and Reading Bitmaps/Images from Internal memory in Android

Alyoshak
  • 2,696
  • 10
  • 43
  • 70
  • did you ask for permissions? what version of Android are you running? – diegoveloper Jan 04 '18 at 22:16
  • I'm running 7.0 – Alyoshak Jan 04 '18 at 22:17
  • There is no `WRITE_INTERNAL_STORAGE` permission. Does LogCat show anything? – CommonsWare Jan 04 '18 at 22:29
  • @CommonsWare, no LogCat shows nothing. It just fails. – Alyoshak Jan 04 '18 at 22:32
  • Hmmmm... try using `compress()` to a `ByteArrayOutputStream`. If that too returns `false`, that indicates there is something odd about the `Bitmap` (e.g., it uses the alpha channel, and JPEG does not support transparency). Or, try `compress()` to a PNG file, and see if that works. – CommonsWare Jan 04 '18 at 22:45
  • Bizarre. I cannot get this to fail now. I went back to original code (external storage) to make sure that still worked. It did. Then used Undo to go back to my original effort at internal storage (presented in this question) and it does not fail. Baffling. Not sure what to do with this question now. – Alyoshak Jan 05 '18 at 17:04

1 Answers1

0

If you are running Android 6.0 >= you have to ask for permissions before you write into the storage.

Refer to this documentation Ask for permissions

diegoveloper
  • 93,875
  • 20
  • 236
  • 194