How to Add Image in Android Jetpack Compose

By Mohammed Rashid •  August 25th, 2022 • 

Jetpack Compose is a toolkit to define the UI of an Android app in a declarative way. This is a short Android app development tutorial to show how to add images in Jetpack Compose.

First of all import an image to your Android project using Android Studio. Firstly, declare your resource Id and then load the image using Image composable. Assign your Id to the painter parameter. See the code snippet given below.

@Composable
fun Greeting() {
    val image = painterResource(id = R.drawable.dog)
    Image(painter = image, contentDescription = null)
}

I used an image of a dog. Following is the complete code to show the image.

package com.example.birthdaycard

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import com.example.birthdaycard.ui.theme.BirthdayCardTheme

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

@Composable
fun Greeting() {
    val image = painterResource(id = R.drawable.dog)
    Image(painter = image, contentDescription = null)
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    BirthdayCardTheme {
        Greeting()
    }
}

Following is the output.

I hope this Android tutorial using Jetpack compose to show an image will be helpful for you.

Mohammed Rashid

Keep Reading