Download image from URL in Kotlin

Needone App
2 min readFeb 20, 2023

--

In Android, we can get the image from synchronously and asynchronously, but it is more common to see in the later.

Download image synchronously

To download an image from a URL in Kotlin, you can use the URL class and the readBytes function from the kotlin.io library. The URL class represents a uniform resource locator and provides methods for creating and parsing URLs. The readBytes function can be used to read the contents of a file or a stream as a byte array.

Here’s an example of how to use the URL and readBytes to download an image from a URL in Kotlin:

import java.net.URL
import kotlin.io.readBytes

fun main() {
val url = URL("https://www.example.com/image.png")
val imageData = url.readBytes()
// TODO: Save the image data to a file or display it in an ImageView
}

In this example, we create a URL object using the URL of the image as a string. We then use the readBytes function to read the contents of the URL as a byte array. The byte array contains the data for the image, which can then be saved to a file or displayed in an ImageView.

Download image asynchronously

To download an image from a URL in Kotlin asynchronously, you can use a coroutine combined with above method. For more

import kotlinx.coroutines.*
import java.net.URL
import kotlin.io.readBytes

fun main() {
// Create a new coroutine scope
val scope = CoroutineScope(Dispatchers.Default)

// Launch a new coroutine in the scope
scope.launch {
val url = URL("https://www.example.com/image.png")
val imageData = url.readBytes()
// TODO: Save the image data to a file or display it in an ImageView
}
}

In this example, we create a new coroutine scope using the Dispatchers.Default dispatcher, which runs the coroutine on a shared background thread pool. We then launch a new coroutine in the scope using the launch function. Inside the coroutine, we create a URL object using the URL of the image as a string and use the readBytes function to read the contents of the URL as a byte array. The byte array contains the data for the image, which can then be saved to a file or displayed in an ImageView.

Originally published at https://needone.app on February 20, 2023.

--

--

No responses yet