Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use TYPE_BYTE_GRAY to efficiently create a grayscale bufferedimage using AWT

I need to create a grayscale image from data in an nio ShortBuffer. I have a function that maps the data in the ShortBuffer to unsigned byte but is in an int (easily changed). The method I found uses an RGB plus transparency color model and appears to be quite inefficent. i have not been able to see how to apply the TYPE_BYTE_GRAY and modify the code. i'm new to Java. Here's my code:

    public void paintComponent(Graphics g) {
    final BufferedImage image;
    int[] iArray = {0, 0, 0, 255};  //  pixel

    image = (BufferedImage) createImage(WIDTH, HEIGHT);

    WritableRaster raster = image.getRaster();
    sBuf.rewind();  // nio ShortBuffer
    for (int row = 0; row < HEIGHT; row++) {
        for (int col = 0; col < WIDTH; col++) {
            int v = stats.mapPix(sBuf.get());  // map short to byte
            iArray[0] = v;  // RGBT
            iArray[1] = v;  
            iArray[2] = v;
            raster.setPixel(col, row, iArray);
        }
    }
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}

TIA Nate

like image 966
Nate Lockwood Avatar asked Oct 23 '25 04:10

Nate Lockwood


1 Answers

Insted of using a ColorConvertOp, you could simply create a new gray scale BufferedImage and paint the original colored image onto it:

public static BufferedImage convertToGrayScale(BufferedImage image) {
  BufferedImage result = new BufferedImage(
            image.getWidth(),
            image.getHeight(),
            BufferedImage.TYPE_BYTE_GRAY);
  Graphics g = result.getGraphics();
  g.drawImage(image, 0, 0, null);
  g.dispose();
  return result;
}

This should perform significantly faster and give better results than using the filter() method.

A great tuturial (including instruction on how to use a GrayFilter) can be found here: http://www.tutorialized.com/tutorial/Convert-a-Color-Image-to-a-Gray-Scale-Image-in-Java/33347

like image 102
Clayton Louden Avatar answered Oct 25 '25 17:10

Clayton Louden



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!