繁体   English   中英

在Java中显示矩阵中的灰度图像

[英]Display a gray scale image from a matrix in Java

我正在尝试读取一个文件,其中有一个表示图像单色的矩阵,像这样在JAVA中使用BufferedImage

    final BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_GRAY);
    Graphics2D g = (Graphics2D)img.getGraphics();
    ... /*reading from file*/ 
    try (InputStream in = new FileInputStream("file.mac");
         Reader reader = new InputStreamReader(in, encoding);
         // buffer for efficiency
         Reader buffer = new BufferedReader(reader)) {
        int r;
        int i=0;
        int j=0;
        while ((r = buffer.read()) != -1) {
             g.setColor(new Color(?,?,?)); 
             g.fillRect(i, j, 1, 1);
             i++;
             if(i==WIDTH){
                 j++;
                 i=0;
             }
       }
    }

问题是我将在此行中设置颜色g.setColor(new Color(?,?,?)); get in r变量,表示矩阵中的灰度等级。

您必须将红色,绿色和蓝色的颜色参数设置为相同的值,以存档灰色。 Color构造函数接受[0,255]之间的RGB值,因此您将不得不缩放r值以匹配[0,255]缩放比例:

int grey = r/rMax * 255 //Gives you a grey value between [0, 255];

rMax是文件中最大的r值。

然后将颜色设置为

g.setColor(new Color(grey, grey, grey));

为了使整个过程更有效率,我建议先创建一个灰色数组,以避免创建大量重复的Color对象:

Color[] colors = new Color[256];

for (int i = 0; i <=255; i++) {
    colors[i] = new Color(i, i, i);
}

然后将循环中的Color设置为

g.setColor(colors[grey]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM