Search code examples
javacmdjoptionpanejavax.imageio

Downloading, Saving and previewing image on JOptionPane


I am creating a modern command-line application, it takes command and gives values, I have created many commands, the thing I need to know is how I can download an image from the internet, save it in a file, then preview that image on JOptionPane(JFrame), as for a virtual code, I want this to happen:

// REGULAR JAVA:
String link = JOptionPane.showInputDialog(null, "Enter The Link of the image:");
String directoryToBeSavedIn = JOptionPane.showInputDialog(null, "Enter directory");
// What I need:
saveImage(link, directoryToBeSavedInAndName); // Download and save( e.g. C:\Down.png )
Image downloadedImage = new Image(directoryToBeSavedInAndName); // Specifies an Image type object, that is the downloaded Image
JOptionPane.showPicture(downloadedImage); // this calls the JOptionPane, with showPicture as a panel that will show a picture to the user.

Unreal Codes: saveImage();, Image .. = new Image();, showPicture();


Solution

  • Given this class you have (at least) two ways to display the image:

    public static class PictureView extends JFrame {
    
        public PictureView(ImageIcon image) {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            JLabel labelImage = new JLabel(image);
            panel.add(labelImage);
            setContentPane(panel);
        }
    
    }
    

    (1) Directly without downloading to your filesystem:

        try {
            URL imageUrl = new URL("http://domain/oneimage.png"); // your URL or link
            PictureView view = new PictureView(new ImageIcon(imageUrl));
            view.pack();
            view.setVisible(true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    (2) Or by downloading first:

        try {
            URL imageUrl = new URL("http://domain/anotherimage.png"); // your URL or link
            InputStream in = imageUrl.openStream();
            Path outputPath = Paths.get("downloaded.png"); // your directoryToBeSavedInAndName
            Files.copy(in, outputPath, StandardCopyOption.REPLACE_EXISTING);
            PictureView view = new PictureView(new ImageIcon("downloaded.png"));  // your directoryToBeSavedInAndName
            view.pack();
            view.setVisible(true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }