java - 如何使用二值图像处理绘制 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();
}
}
解决方案
如果您有一个数据结构来保存 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));
推荐阅读
- scheme - 无法在简单方案中打印 ANSI 转义码
- android - Jetpack Compose 中的材质图标大小调整?
- git - 从 GCP VM 执行 git push 时出现 Google Source Repository 错误
- javascript - 如何避免 Superagent 响应解析异步功能
- linux - 使用新主机名的 EC2 框 ssh
- mysql - 如何为多列 MySQL 设置 UNIQUE 约束?
- ios - 上下文菜单破坏性操作,SwiftUI
- reactjs - React JS:将值从路由传递到组件
- oracle - 未使用可传输表空间复制的列
- asp.net-mvc - 如何将 Mvc 路由空间(如“%20”)更改为“-”