如何使用 TYPE_BYTE_GRAY 使用 AWT 高效创建灰度缓冲图像
我需要根据 nio ShortBuffer 中的数据创建灰度图像。我有一个函数,可以将 ShortBuffer 中的数据映射到无符号字节,但采用 int 形式(很容易更改)。我发现的方法使用 RGB 加透明度颜色模型,看起来效率很低。我无法了解如何应用 TYPE_BYTE_GRAY 并修改代码。我是 Java 新手。这是我的代码:
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 内特
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代替使用 ColorConvertOp,您可以简单地创建一个新的灰度 BufferedImage 并将原始彩色图像绘制到其上:
这应该比使用 filter() 方法执行得更快并且给出更好的结果。
一个很棒的教程(包括如何使用 GrayFilter< /a>)可以在这里找到:http://www.tutorialized.com/tutorial/Convert-a-Color-Image-to-a-Gray-Scale-Image-in-Java/33347
Insted of using a ColorConvertOp, you could simply create a new gray scale BufferedImage and paint the original colored image onto it:
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
一种方法是创建
BufferedImage
通过像现在一样写入光栅来实现。一旦你有了BufferedImage
,您可以使用
filter()
方法 < a href="http://java.sun.com/javase/6/docs/api/java/awt/image/ColorConvertOp.html" rel="nofollow noreferrer">ColorConvertOp
,如本示例所示。One approach would be to create the
BufferedImage
by writing to the raster as you are doing now. Once you have theBufferedImage
, you can convert it toTYPE_BYTE_GRAY
using thefilter()
method ofColorConvertOp
, as shown in this example.