How to use TYPE_BYTE_GRAY to efficiently create a grayscale bufferedimage using AWT
Solution 1
One approach would be to create the BufferedImage
by writing to the raster as you are doing now. Once you have the BufferedImage
, you can convert it to TYPE_BYTE_GRAY
using the filter()
method of ColorConvertOp
, as shown in this example.
Solution 2
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
Nate Lockwood
I work at a US federal laboratory and participate in research using an aircraft with several imaging radiometers (research grade cameras with band pass filters and other modifications) so that we can acquire synchronized images - mostly infrared. Our main research thrust is studying wildfires. I'm in a project to upgrade our equipment, computer, and system. Since our contract engineer doesn't know C/C++ I've been teaching myself Java, HTML5, CSS3, and Dart attempting write software to provide a operator's GUI which controls the other computers and cameras on the aircraft LAN. I'm now concentrating on R to, agglomerate data and provide statistic analysis and plots of our data. My title is Ecologist.
Updated on June 05, 2022Comments
-
Nate Lockwood almost 2 years
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