RGB image to grayscale java

In various cases, you may need to convert the RGB images to grayscale or black and white, for example, in image processing, etc. In accordance with that, in this article, you will learn how to convert an RGB image to grayscale using Java. Moreover, the article will cover grayscaling and binarization of the images explicitly.

Java Color Image to Grayscale Converter - Free Download

In order to convert RGB images to grayscale, we’ll use Aspose.Imaging for Java. It is a Java image processing API that allows you to manipulate popular image formats seamlessly. You can either download the API or install it using the following Maven configurations.

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>http://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-imaging-java</artifactId>
    <version>21.7</version>
    <classifier>jdk16</classifier>
</dependency>

Convert an RGB Image to Grayscale in Java

The following are the steps to convert an RGB image to grayscale in Java.

The following code sample shows how to convert an image to grayscale in Java.

Input Image

The following is a sample image used in this article.

image to grayscale Java

Converted to Grayscale

The following is the image after conversion to grayscale.

grayscale image

Java Save Image as Black and White with Binarization

In binarization, each pixel in an image can have only two possible values; 0 or 1. Here, 0 denotes the absence and 1 denotes the presence of the color. Aspose.Imaging supports two binarization methods i.e. binarization with fixed and binarization with Otsu threshold.

Binarization with Fixed Threshold

The following are the steps to perform binarization on an image using fixed threshold.

The following Java code applies binarization to an image and converts it to black and white.

Binarization with Otsu Threshold

The following are the step to convert an image to black and white with Otsu threshold.

The following code sample shows how to convert an image to black and white with Otsu threshold using Java.

Color Image to Grayscale Java Converter - Get a Free License

You can get a free temporary license in order to use the API without evaluation limitations.

Conclusion

In this article, you have learned how to convert a color image to grayscale and black and white using Java. Moreover, you have seen how to apply binarization to the images with fixed or Otsu threshold. In addition, you can explore more about the Java image processing API using documentation. Also, you can share your queries with us via our forum.

See Also