Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an image to black and white ( not gray scal)

hello I am converting an image from color to pure black and white the result is a dark image. I am not getting the reason. Following is my code its been inspired by other codes on SO. Any guidance would be helpfull.

BufferedImage coloredImage = ImageIO.read(new File("/home/discusit/ninja.png"));
BufferedImage blackNWhite = new BufferedImage(coloredImage.getWidth(),coloredImage.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphics = blackNWhite.createGraphics();
graphics.drawImage(blackNWhite, 0, 0, null);

I am not getting what I am doing wrong. Any more ideas using any other open source library would be fine.

WORKING :::::

BufferedImage coloredImage = ImageIO.read(new File("/home/abc/ninja.png"));
BufferedImage blackNWhite = new BufferedImage(coloredImage.getWidth(),coloredImage.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphics = blackNWhite.createGraphics();
graphics.drawImage(coloredImage, 0, 0, null);

ImageIO.write(blackNWhite, "png", new File("/home/abc/newBlackNWhite.png"));
like image 457
Bilbo Baggins Avatar asked Nov 19 '25 18:11

Bilbo Baggins


1 Answers

If you want control over the so-called thresholding process, here a ready-to-use snippet. Start with 128 as a threshold, then you get what the other methods do.

/**
 * Converts an image to a binary one based on given threshold
 * @param image the image to convert. Remains untouched.
 * @param threshold the threshold in [0,255]
 * @return a new BufferedImage instance of TYPE_BYTE_GRAY with only 0'S and 255's
 */
public static BufferedImage thresholdImage(BufferedImage image, int threshold) {
    BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    result.getGraphics().drawImage(image, 0, 0, null);
    WritableRaster raster = result.getRaster();
    int[] pixels = new int[image.getWidth()];
    for (int y = 0; y < image.getHeight(); y++) {
        raster.getPixels(0, y, image.getWidth(), 1, pixels);
        for (int i = 0; i < pixels.length; i++) {
            if (pixels[i] < threshold) pixels[i] = 0;
            else pixels[i] = 255;
        }
        raster.setPixels(0, y, image.getWidth(), 1, pixels);
    }
    return result;
}
like image 186
Mathias Avatar answered Nov 22 '25 08:11

Mathias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!