0

The code below generates gray scale image perfectly for 8 bit depth.If i replace my image file by 16 bit depth or 32 bit depth ,the if statement is triggered.Is there any other way to perfectly covert the 16 and 32 bit depth image or any other solution?

package test;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.io.File;
import javax.imageio.ImageIO;

/**
*
* @author sumit
*/
public class Test {

BufferedImage image;
int width;
int height;

 public Test() {
    try {
        File input = new File("abc.png");
        image = ImageIO.read(input);
        width = image.getWidth();
        height = image.getHeight();

        for (int i = 0; i < height; i++) {

            for (int j = 0; j < width; j++) {

                Color c = new Color(image.getRGB(j, i));
                int red = (int) (c.getRed() * 0.299);
                int green = (int) (c.getGreen() * 0.587);
                int blue = (int) (c.getBlue() * 0.114);
                Color newColor = new Color(red + green + blue,
                        red + green + blue, red + green + blue);

                image.setRGB(j, i, newColor.getRGB());
            }
        }

        int widths = image.getWidth();
        int heights = image.getHeight();

        // Get raw image data
        Raster raster = image.getData();
        DataBuffer buffer = raster.getDataBuffer();
        DataBufferByte byteBuffer = (DataBufferByte) buffer;
        byte[] srcData = byteBuffer.getData(0);
        if (widths * heights != srcData.length) {
       System.err.println("Unexpected image data size. Should be greyscale image");
            System.exit(1);
        }
        File ouptut = new File("grayscale.png");
        ImageIO.write(image, "png", ouptut);

    } catch (Exception e) {
    }
  }

  static public void main(String args[]) throws Exception {
    Test obj = new Test();
  }

 }

1 Answers1

2

You should multiply by bpp ( bytes per pixel ):

if (widths * heights * bpp != srcData.length) 
  • For 8 bit depth - bpp is 1
  • For 16 bit depth - bpp is 2
  • For 32 bit depth - bpp is 4
napuzba
  • 5,255
  • 3
  • 17
  • 30
  • Thanks.By doing this it does not triggers the if statement. but i am doing further binarization by otsu method it results unappropriate result... – sumit gautam May 01 '17 at 05:06