How to save an url image in internal storage in Kotlin?

-1

How do I save an image that I receive in a url in the internal storage of android so that it can be seen in the smartphone gallery?

Example, my app receives an image type " link " and when a button is pressed, it is saved in the memory.

Thanks for the help

    
asked by carlosdag28 02.04.2018 в 13:38
source

1 answer

0

you could try these 2 methods, first convert the url into a Bitmap and then that Bitmap you keep it in local, I hope it serves you

fun getBitmapFromURL(src: String): Bitmap? {
    try {
        val url = URL(src)
        val connection = url.openConnection() as HttpURLConnection
        connection.setDoInput(true)
        connection.connect()
        val input = connection.getInputStream()
        return BitmapFactory.decodeStream(input)
    } catch (e: IOException) {
        // Log exception
        return null
    }

}

private fun saveToInternalStorage(name : String, bitmapImage: Bitmap, context: Context): String {
    val cw = ContextWrapper(context.applicationContext)
    // path to /data/data/yourapp/app_data/imageDir
    val directory = cw.getDir("imageDir", Context.MODE_PRIVATE)
    // Create imageDir
    Log.d("PATH", directory.path)
    val mypath = File(directory, name+".jpg")

    var fos: FileOutputStream? = null
    try {
        fos = FileOutputStream(mypath)
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos)
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        try {
            fos!!.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }
    return directory.absolutePath
}
    
answered by 16.04.2018 в 01:12