How to Show Image from URL in Android using Jetpack Compose

By Mohammed Rashid •  August 31st, 2022 • 

Jetpack Compose is a popular toolkit from Android that helps to create UIs at a good speed. In this blog post, let’s check how to add an image from a web URL using the Jetpack Compose.

Coil is an image loading library for Android. Here, we use coil to load an image from a URL in Jetpack Compose.

First of all, add the following dependency to Gradle Scriptsbuild.gradle module file. The dependency must be inside the dependencies {} tag. Make sure you are using the latest version of the library as the version of the library always changes.

implementation("io.coil-kt:coil-compose:2.2.0")

Don’t forget to add Internet permission to your Android Manifest file.

<uses-permission android:name="android.permission.INTERNET" />

Using coil you can load images asynchronously. Use AsyncImage composable from Coil to show an image. See the code snippet given below.

import coil.compose.AsyncImage

AsyncImage(model = "https://cdn.pixabay.com/photo/2021/11/12/12/16/leaves-6788800_1280.jpg",
            contentDescription = null)

Following is the complete code to add an image from the URL in Jetpack Compose.

package com.example.example

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import coil.compose.AsyncImage
import com.example.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    imageExample()
                }
            }
        }
    }
}

@Composable
fun imageExample() {
    Box() {
        AsyncImage(model = "https://cdn.pixabay.com/photo/2021/11/12/12/16/leaves-6788800_1280.jpg",
            contentDescription = null)
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ExampleTheme {
        imageExample()
    }
}

The output is given below.

I hope this Jetpack Compose tutorial is helpful for you.

Mohammed Rashid

Keep Reading