0

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();
davide
  • 1,918
  • 2
  • 20
  • 30
  • 1
    Check [*this example*](http://stackoverflow.com/questions/14513542/convert-image-to-black-white/14513703#14513703) – MadProgrammer Sep 12 '13 at 07:41
  • @MadProgrammer I posted an answer below, but I realize most of it is covered well in your link. – Harald K Sep 12 '13 at 20:25
  • 1
    Dithering to bitonal would be a bad idea for faxes because it will increase the size of the compressed data. What you probably want to use is a dynamic thresholding algorithm which can handle subtle color differences and produce a good looking image. – BitBank Sep 13 '13 at 15:46

2 Answers2

2

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.

Harald K
  • 26,314
  • 7
  • 65
  • 111
1
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

Community
  • 1
  • 1
Nambi
  • 11,944
  • 3
  • 37
  • 49
  • My aim is to convert a normal image to tiff image.This tiff format is used for faxing.For this reason i am using compression group 4 when creating tiff file from BufferedImage.If dont use BufferedImage.TYPE_BYTE_BINARY,then i get the below error. Exception in thread "main" java.lang.Error: Bilevel encodings are supported for bilevel images only. When i use it,then tiff file is created but some dark colors overlap.My total code is below. – user2761226 Sep 12 '13 at 08:14