簡體   English   中英

如何使用 Kotlin 中的協程將圖像保存在設備中

[英]How to save an image in device using Coroutines in Kotlin

我正在研究繪圖應用程序項目,我做到了。 但最后,我需要將該圖像保存在設備上。 我用谷歌搜索了它,發現了現在已棄用的 AsyncTask 示例。 那么任何人都可以幫助我如何處理 Kotlin 中的協程嗎? 我知道協程是 AsyncTask 的替代品。

我的意思是這個例子的替代方案。

  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
        }

    }

願這個答案可以幫助您做您想做的事情,將圖像保存在存儲中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM