Android Jetpack Compose – Display Image as Grayscale
We can display given image as a grayscale image, in Android Jetpack Compose.
To display an image as a grayscale image using Image composable in Android Jetpack Compose, use colorFilter
parameter of the Image composable and set the saturation of the ColorMatrix to 0
.
The Image composable to display given image as a grayscale image would be as shown in the following.
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Big Elephant with Inverted Colors",
colorFilter = ColorFilter.colorMatrix(ColorMatrix(colorMatrix))
)
Example Android Application to Display Image as Grayscale Image
In the following example, we display the following image, as a grayscale image, using an Image composable.
sample-image.jpg
![](https://kotlinandroid.org/wp-content/uploads/2023/12/sample_image.jpg)
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(20.dp),
) {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Big Elephant with Grayscale Colors",
colorFilter = ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) })
)
}
}
}
}
}
Screenshot
![Android Jetpack Compose - Display Image as Grayscale](https://kotlinandroid.org/wp-content/uploads/2023/12/image-grayscale-1.webp)
Summary
In this tutorial, we have seen how to display an image as a grayscale image using Image composable in Android Jetpack Compose, with an example.