Tomáš Zato
Tomáš Zato

Reputation: 53161

Easily print image on the screen for debug purposes in a blocking manner

I am working on a computer vision project and somewhere in a process an endless loop happens. It seems that my image data is being corrupted.

In past, I used to save debug results on the disk using this method:

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

The problem is that once loops are used and the error is somewhere inbetween, I need to see many images. So basically, I'd like a method that would be defined like this:

  /** 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) {
   ???
}

And could be called in a loop or any function to show be the actual image, effectively behaving like a break point. Because while multithreading is very good in production code, blocking functions are much better for debugging.

Upvotes: 2

Views: 2663

Answers (1)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51455

You can code something like this. In this example, the image file has to be in the same directory as the source code.

Here's the image displayed in a dialog. You left click the OK button to continue processing.

Display Image

If the image is bigger than your screen, scroll bars will appear to let you see the whole image.

In your code, since you already have the Image, you can just copy and paste the displayImage method.

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

}

Upvotes: 6

Related Questions