在JOptionPane上下载,保存和预览图像

时间:2015-11-02 16:29:20

标签: java cmd joptionpane javax.imageio

我正在创建一个现代命令行应用程序,它需要命令并提供值,我创建了许多命令,我需要知道的是我如何从互联网上下载图像,将其保存在文件中,然后在JOptionPaneJFrame)上预览该图片,就虚拟代码而言,我希望这种情况发生:

// 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.

虚幻代码: saveImage(); Image .. = new Image(); showPicture();

1 个答案:

答案 0 :(得分:1)

鉴于此课程,您(至少)有两种方式来显示图像:

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)直接无需下载到您的文件系统:

    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)或首先下载:

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