Convert Image to Black and White using Java
This example demonstrates how to convert an image to Black and White using Java. A 1-bit
image is created with an IndexColorModel
with two colors in the default sRGB
ColorSpace
: {0,0,0}
and {255,255,255}
.
Convert Image to Black and White
We can obtain a BufferedImage
by using the ImageIO.read()
method.
Next, we create a new BufferedImage
with the same dimensions as the original and most impotently we pass in the BufferedImage.TYPE_BYTE_BINARY
. This represents an image with 1-bit
RGB
colors: {0,0,0}
and {255,255,255}
. Finally, we draw the image using the Graphics2D.drawImage()
method. The fourth argument Color.WHITE
‘ll replace the transparent layer of a PNG
into a default background.
package com.memorynotfound.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ConvertBlackWhite {
public static void main(String... args) {
try {
File input = new File("/tmp/java-duke.png");
BufferedImage image = ImageIO.read(input);
BufferedImage result = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphic = result.createGraphics();
graphic.drawImage(image, 0, 0, Color.WHITE, null);
graphic.dispose();
File output = new File("/tmp/java-duke-black-white.png");
ImageIO.write(result, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Converted Images
To demonstrate the result, we added the following table. You can see that the result is rendered in only pure black and white 1-bit
colors: {0,0,0}
and {255,255,255}
.
duke.png (original) | duke-black-white.jpg |
---|---|
Background: transparent | Background: white |
Size: 9KB | Size: 1KB |
Thank you so much !!!
Thanks for your help!