Tom*_*ica 2 java debugging bufferedimage
我正在研究一个计算机视觉项目,并在某个过程中发生无限循环.我的图像数据似乎已被破坏.
过去,我曾经使用这种方法在磁盘上保存调试结果:
public static boolean saveToPath(String path, BufferedImage image) {
File img = new File(path);
try {
ImageIO.write(image, "png", new File(path));
} catch (IOException ex) {
System.err.println("Failed to save image as '"+path+"'. Error:"+ex);
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
问题是,一旦使用循环并且错误介于两者之间,我需要看到许多图像.所以基本上,我想要一个像这样定义的方法:
/** Displays image on the screen and stops the execution until the window with image is closed.
*
* @param image image to be displayed
*/
public static void printImage(BufferedImage image) {
???
}
Run Code Online (Sandbox Code Playgroud)
并且可以在循环或任何函数中调用以显示实际图像,有效地表现为断点.因为虽然多线程在生产代码中非常好,但阻塞函数对于调试来说要好得多.
你可以编写这样的代码.在此示例中,图像文件必须与源代码位于同一目录中.
这是对话框中显示的图像.您左键单击确定按钮继续处理.

如果图像大于屏幕,则会出现滚动条,让您看到整个图像.
在您的代码中,由于您已经拥有了Image,因此您只需复制并粘贴displayImage方法即可.
package com.ggl.testing;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class DisplayImage {
public DisplayImage() {
displayImage(getImage());
}
private Image getImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void displayImage(Image image) {
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel = new JPanel();
panel.add(label);
JScrollPane scrollPane = new JScrollPane(panel);
JOptionPane.showMessageDialog(null, scrollPane);
}
public static void main(String[] args) {
new DisplayImage();
}
}
Run Code Online (Sandbox Code Playgroud)