我正在尝试使用Java进行小型图像处理。用户应该能够加载图像并通过单击按钮添加一些简单的图像修改。 加载和显示图像没有问题但是当我尝试从中创建二进制图像时,repaint()方法使我在屏幕上显示黑色图像。 我认为问题在于repaint() - 方法。我已经使用了搜索功能和Google,但我仍然不知道我的代码中有什么问题。 这就是我到目前为止所做的:
public class ImageProcessing extends JFrame implements ActionListener {
private JPanel imagePanel;
private JPanel buttonPanel;
private JButton binaryButton;
private JButton loadButton;
private BufferedImage image;
private final String WINDOW_TITLE = "Image Processing";
public ImageProcessing() {
createWindow();
}
private void createWindow() {
this.setTitle(WINDOW_TITLE);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
imagePanel = new ImagePanel();
buttonPanel = new JPanel();
this.add(imagePanel, BorderLayout.CENTER);
loadButton = new JButton("Load image");
loadButton.addActionListener(this);
buttonPanel.add(loadButton);
this.add(buttonPanel, BorderLayout.SOUTH);
binaryButton = new JButton("binary");
binaryButton.addActionListener(this);
buttonPanel.add(binaryButton);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.loadButton) {
String filePath = getImageFile();
if (filePath != null) {
try {
image = ImageIO.read(new File(filePath));
// imageBackup = image;
} catch (IOException e1) {
e1.printStackTrace();
}
this.repaint();
}
} else if (e.getSource() == this.binaryButton) {
image = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
imagePanel = new ImagePanel();
this.repaint();
}
}
private String getImageFile() {
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
File file = null;
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
return file.getPath();
} else
return null;
}
class ImagePanel extends JPanel {
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
}
我希望你能帮助我并解释我做错了什么。提前谢谢。
答案 0 :(得分:3)
目前尚不清楚您正在尝试进行何种图像处理。代码..
image = new BufferedImage(
image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
..仅创建一个具有字节二进制类型的新(空白)图像。你没有画任何东西。这就是为什么它是黑色的。
要绘制它(例如尝试复制原始图像),您可以获得图形上下文:
Graphics2D g = image.createGraphics();
然后用以下内容复制:
g.drawImage(otherImage, 0, 0, this);
我不确定Java是否或如何从全深度RGB图像转换为TYPE_BYTE_BINARY
。你可能会遇到例外。
答案 1 :(得分:1)
您正在替换图像面板而不是图像。此外,您没有在二进制图像上执行实际绘制。以下是如何将原始图像转换为二进制文件的示例,它基于提供的代码:
else if (e.getSource() == this.binaryButton) {
BufferedImage mask = new BufferedImage(image.getWidth(),
image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
Graphics g = mask.getGraphics();
g.drawImage(image, 0, 0, this);
g.dispose();
image = mask;
this.repaint();
}