2015-11-02 37 views
0

我正在創建一個現代命令行應用程序,它需要命令並給出值,我創建了許多命令,我需要知道的是我如何從互聯網下載圖像,它保存在一個文件,然後預覽在JOptionPaneJFrame)的形象,作爲一個虛擬的代碼,我希望這種情況發生:在JOptionPane上下載,保存和預覽圖像

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

鑑於這個類,你有(至少)兩種方式來顯示圖像:

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