gpt4 book ai didi

java - 重绘 BufferedImage

转载 作者:行者123 更新时间:2023-11-30 07:20:24 25 4
gpt4 key购买 nike

我正在尝试使用 Java 进行小型图像处理。用户应该能够加载图像并通过单击按钮对图像添加一些简单的修改。加载和显示图像没有问题,但是当我尝试用它制作二进制图像时,repaint() 方法使我在屏幕上变成黑色图像。我认为问题出在 repaint() 方法上。我已经使用了搜索功能和谷歌,但我仍然不知道我的代码有什么问题。这就是我到目前为止所拥有的:

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);
}
}
}

我希望你能帮助我并解释我做错了什么。提前致谢。

最佳答案

目前尚不清楚您要进行何种图像处理。代码..

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。您可能会遇到异常。

关于java - 重绘 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14059302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com