user2761226
user2761226

Reputation: 21

Convert colored image to back/white image

I am working on converting colored image to black and white image. I am using BufferedImage for this with the type of TYPE_BYTE_BINARY. But output image is not converted correctly. For example, if image contains blue letters on black background, result image for this part is totaly black. Can anybody help me? My code is below.

//Invert the colormodel
byte[] map = new byte[] { (byte) (255), (byte) (0) };
IndexColorModel colorModel = new IndexColorModel(1, 2, map,
map, map);

BufferedImage bufferedImage = new BufferedImage(
img.getWidth(null), img.getHeight(null),
BufferedImage.TYPE_BYTE_BINARY, colorModel);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(img, 0, 0, null);
g2.dispose();

Upvotes: 0

Views: 1781

Answers (2)

Harald K
Harald K

Reputation: 27054

Blue has a very low intensity, so blue (like RGB(0, 0, 255)) turning out black when converted to b/w with 50% threshold is to be expected. Try brightening the original image before converting to b/w, to increase the parts of the image coming out white.

You can use RescaleOp to brighten the image prior to conversion, or pass an instance along with your image to the drawImage method that takes a BufferedImageOp as parameter. Note that you can scale the R, G and B values independently.

Upvotes: 2

Nambi
Nambi

Reputation: 12042

BufferedImage bufferedImage= new BufferedImage(img.getWidth(null), img.getHeight(null); 
    ColorConvertOp op = 
        new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
    op.filter(bufferedImage, bufferedImage);

check this link

Upvotes: 1

Related Questions