Search code examples
androidandroid-studioandroid-bitmapandroid-gallery

How to save bitmap in custom gallery?


I have understood that I can create a folder in DCIM and if there is a file in it, the dir is displayed as an album name. I can create the dir just fine, in this case, I call the dir "ThoughtCast."

I try saving a PNG file, however, and it does not appear.

Here is my code:

   public void savebitmap(Bitmap bmp) throws IOException {

        String file_path =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "ThoughtCast/";

        File dir = new File(file_path);
        if(!dir.exists())
            dir.mkdirs();
        File file = new File(dir, "sketchpad"  + ".png");
        FileOutputStream fOut = new FileOutputStream(file);

        bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();

    }

Any help will be appreciated. Thanks


Solution

  • Try this it may help you (it's in kotlin)

    I am currently do this task

     private fun saveImage(bitmap: Bitmap) {
        var outStream: FileOutputStream? = null
        // Write to SD Card
        try {
            val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "ThoughtCast/")
            dir.mkdirs()
            val fileName = String.format("%s_%d.jpg", "Image", System.currentTimeMillis())
            val outFile = File(dir, fileName)
            outStream = FileOutputStream(outFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
            outStream.flush()
            outStream.close()
            Utils.showSnackBar(binding.rootView, getString(R.string.image_saved))
        } catch (e: FileNotFoundException) {
            Crashlytics.logException(e)
        } catch (e: IOException) {
            Crashlytics.logException(e)
        } finally {
        }
    }