0

I am trying to save a taken image from the camera activity to the gallery so i made a function for it to do the same.Though the app is running but the image is not getting saved in the gallery.Can Anyone Help, please.

here I created the function in kotlin

 private fun saveImageToGallery(bitmap: Bitmap) {

    val file: File = Environment.getExternalStorageDirectory()
    val dir = File(file.absolutePath + "/MyImageEditorTasks/")
    dir.mkdirs()
    val filename = String.format("${System.currentTimeMillis()}.jpeg")
    val outfile = File(dir, filename)
    var outputstream: FileOutputStream? = null
    try {
        outputstream = FileOutputStream(outfile)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputstream)
        outputstream.flush()
        outputstream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }

}

Here I used the same function

 public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == GALLERY) {
            if (data != null) {
                val contentURI = data.data
                try {
                    // Here this is used to get an bitmap from URI
                    val selectedImageBitmap =
                        MediaStore.Images.Media.getBitmap(this.contentResolver, contentURI)
                    saveImageToInternalStorage(selectedImageBitmap)
                    preview!!.setImageBitmap(selectedImageBitmap) // Set the selected image from GALLERY to imageView.
                } catch (e: IOException) {
                    e.printStackTrace()
                    Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show()
                }
            }
            // TODO (Step 7: Camera result will be received here.)
        } else if (requestCode == CAMERA) {
            val thumbnail: Bitmap = data!!.extras!!.get("data") as Bitmap                 
            saveImageToGallery(thumbnail)
            preview!!.setImageBitmap(thumbnail) // Set to the imageView.
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        Log.e("Cancelled", "Cancelled")
    }
}
a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Pulkit Jain
  • 11
  • 1
  • 2
  • Your code saves a bitmap to external storage. Please first tell if it is indeed saved. You can check that with a suitable file manager. And... if your code is correct it would have warned you that the bitmap was not saved.. – blackapps Mar 01 '22 at 12:25
  • `dir.mkdirs()` Dont blindly call mkdirs. That should be: `if (! dir.exists()) if ( !dir.mkdirs()) return null;` Display a Toast() too to inform the user when this happens. – blackapps Mar 01 '22 at 12:26
  • `private fun saveImageToGallery(bitmap: Bitmap) ` Wrong function name as it does not save to Gallery -what ever you mean by that- but to external storage. – blackapps Mar 01 '22 at 12:29
  • @blackapps can you please help me how to do it actually i am new to android development and i am unable to get what you are trying to say,it will be a great help if you provide me some resourses or a demo code so that i can learn the same concept.Thank you sir for comment – Pulkit Jain Mar 01 '22 at 12:42
  • Are you unable to replace that mkdir code with the code i suggested? Are you unable to use a file manager to look for that file? All hard to believe. – blackapps Mar 01 '22 at 12:44
  • Does this answer your question? [Saving a screenshot of a custom view on Android](https://stackoverflow.com/questions/33062202/saving-a-screenshot-of-a-custom-view-on-android) – Ivo Mar 01 '22 at 13:03

1 Answers1

0

You can get from drawble and save it to your gallery. Function example is below.

private fun saveImage(drawable: Drawable) {
    val file = getDisc()

    if (!file.exists() && !file.mkdirs()) {
        file.mkdir()
    }

    val simpleDateFormat = SimpleDateFormat("yyyymmsshhmmss")
    val date = simpleDateFormat.format(Date())
    val name = "IMG" + date + ".jpg"
    val fileName = file.absolutePath + "/" + name
    val newFile = File(fileName)

    try {
        val draw = drawable as BitmapDrawable
        val bitmap = draw.bitmap
        val fileOutPutStream = FileOutputStream(newFile)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutPutStream)
        Toast.makeText(requireContext(), "File saved succesfully", Toast.LENGTH_SHORT)
            .show()
        savedFile = newFile
        fileOutPutStream.flush()
        fileOutPutStream.close()

    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    }

}

private fun getDisc(): File {
    val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
    return File(file, "YOUR_ALBUM_NAME")
}