How to save an image in device using Coroutines in Kotlin

Total
5
Shares

I was working on Drawing App Project and I made it. But at last, I need to save that image on the device. I googled it and I found examples with AsyncTask which is now deprecated. So can anyone help me with how can I do with Coroutines in Kotlin? As I got to know Coroutine is an Alternative to AsyncTask.

I mean alternative for this example.

  private inner class BitmapAsyncTask(val mBitmap: Bitmap): AsyncTask<Any, Void,String>(){
        override fun doInBackground(vararg p0: Any?): String {
            var result = ""
            if(mBitmap != null){
                try{
                    val bytes = ByteArrayOutputStream()
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90, bytes)
                    val f = File(externalCacheDir!!.absoluteFile.toString()
                            + File.separator + "KidsDrawingApp_"
                            + System.currentTimeMillis() / 1000 + ".png")
                    val fos = FileOutputStream(f)
                    fos.write(bytes.toByteArray())
                    fos.close()
                    result = f.absolutePath
                }catch(e: Exception){
                    result = ""
                    e.printStackTrace()
                }
            }
            return result
        }

    }

Solution

May this answer helps you to do what you want to save the image on storage.

Leave a Reply

Your email address will not be published. Required fields are marked *