Today we will show you how we can convert the Image URL to Bitmap using Coil in Jetpack Compose. But before moving forward, I would like to ask you to please follow my account to get the latest updates about Android and other tech-related topics.
What is Coil?
An image loading library for Android backed by Kotlin Coroutines. Coil is:
- - Fast: Coil performs a number of optimizations including memory and disk caching, downsampling the image in memory, automatically pausing/cancelling requests, and more.
- - Lightweight: Coil adds ~2000 methods to your APK (for apps that already use OkHttp and Coroutines), which is comparable to Picasso and significantly less than Glide and Fresco.
- - Easy to use: Coil’s API leverages Kotlin’s language features for simplicity and minimal boilerplate.
- - Modern: Coil is Kotlin-first and uses modern libraries including Coroutines, OkHttp, Okio, and AndroidX Lifecycles.
Implementation:
I have made this example in Jetpack Compose, but we can also do this without Jetpack Compose. Let’s create an Activity:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackComposeUtilsTheme {
val scope = rememberCoroutineScope()
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
urlToBitmap(
scope = scope,
imageURL = "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg",
context = LocalContext.current,
onSuccess = {
it
},
onError = {
it
}
)
}
}
}
}
}
We have created a method i.e: urlToBitmap, which takes some parameters like coroutine scope, image URL, and context. It also gives the callback in case of Success and Error.
We are using rememberCoroutineScope() for getting the CoroutineScope instance to pass in our function to load the image data using Dispatchers.IO.
fun urlToBitmap(
scope: CoroutineScope,
imageURL: String,
context: Context,
onSuccess: (bitmap: Bitmap) -> Unit,
onError: (error: Throwable) -> Unit
) {
var bitmap: Bitmap? = null
val loadBitmap = scope.launch(Dispatchers.IO) {
val loader = ImageLoader(context)
val request = ImageRequest.Builder(context)
.data(imageURL)
.allowHardware(false)
.build()
val result = loader.execute(request)
if (result is SuccessResult) {
bitmap = (result.drawable as BitmapDrawable).bitmap
} else if (result is ErrorResult) {
cancel(result.throwable.localizedMessage ?: "ErrorResult", result.throwable)
}
}
loadBitmap.invokeOnCompletion { throwable ->
bitmap?.let {
onSuccess(it)
} ?: throwable?.let {
onError(it)
} ?: onError(Throwable("Undefined Error"))
}
}
We load the image inside the coroutine scope and give a callback on its completion. We cancel the coroutine job in case of ErrorResult and pass the error message and throwable to the coroutine cancel() function.
After the coroutine job is completed, we got the callback on invokeOnCompletion. We checked whether the bitmap object is null or not, if it is not null, we call the onSuccess otherwise we call the onError.
Project Github Link: https://github.com/arsalankhan994/jetpack-compose-utils
That’s it for now. I will cover more topics on Android, Java, Kotlin, and Springboot in my upcoming articles. If you like this article then Clap as much as you can 🤐
In case you missed: 🤐
- https://towardsdev.com/parallel-multiple-api-calls-or-network-calls-using-kotlin-coroutines-40cb5f313171
- https://erselankhan.medium.com/communication-between-modules-in-android-erselan-khan-2c2ae5684024
- https://medium.com/bazaar-tech/dynamically-update-refresh-reload-viewpager2-fragments-588fcbd6f859
Show your love ❤️ by sharing this article with your fellow developers 😅 and also following my Medium account ✈️
(Follow me for more content about Android, Kotlin, and other technologies. If you have any questions, go ahead and ask me here or email me at arsalankhan994@gmail.com and I’ll do my best to respond.)
Top comments (0)