首页 > 解决方案 > 如何使用二值图像处理绘制 GUI?

问题描述

我正在研究图像处理,但我找不到使用二进制图像读取来绘制 GUI RGB 的方法。我被paintComponent区域困住了。

我可以读取文件但无法将 RGB 值绘制到 GUI。有人可以指导我吗?

这是我到目前为止所做的:

private int ws;
private FileInputStream fis;

mybin(){
    try {
        fis = new FileInputStream("mybin.bin");

        String mn = getMagicNumber();
        System.out.println(mn);

        skipWhitespace();

        int width = readNumber();
        System.out.println(width);

        skipWhitespace();

        int height = readNumber();
        System.out.println(height);

        skipWhitespace();
        int maxNum = readNumber();

        System.out.println(maxNum);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch(IOException e2) {}
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(600,600);
    this.setVisible(true);
}
private String getMagicNumber() {
    byte [] magicNum = new byte[2];
    try {
        fis.read(magicNum);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new String(magicNum);
}
private void skipWhitespace() {
    try {
        ws = fis.read();
        while(Character.isWhitespace(ws))
            ws = fis.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private int readNumber() {
    String wstr = "";
    try {
        while(!Character.isWhitespace(ws)) {
            //while(Character.isDigit(ws))
                wstr = wstr + (ws-'0'/*48*/);
                ws = fis.read();
            }
    }catch(IOException e2) {}

    System.out.println(wstr);
    return Integer.parseInt(wstr);
}

class DrawingPanel extends JPanel{
    @Override
    public void paintComponent(Graphics g) {

    }
}
public static void main(String [] args) {
    new mybin();
}
}

标签: javaimageswingbinaryrgb

解决方案


如果您有一个数据结构来保存 RGB 值并希望在屏幕上绘制它们:

首先,您应该首先创建image它们中的一个。像这样的东西:

// Create an image, with given dimensions, and RGB palette...
final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB);
// Paint the RGB values (EG from arrays) to the image
for (int x = 0; x < width; ++x)
  for (int y = 0; y < height; ++y)
  {
    // Convert the R,G,B values to a single int
    final int rgb = r[x,y]*0x10000 + g[x,y]*1x100 + b[x,y];
    // Color the pixel...
    image.setRGB(x, y, rgb);
  }

然后将其显示在您的 GUI 上。
这可以通过创建一个特殊的组件并执行绘画来完成,请参阅c0der的答案。

或者您可以创建一个Icon,并将其添加到任何JLabel

label.setIcon(new ImageIcon(image));

推荐阅读