gpt4 book ai didi

java - 在 JOptionPane 上下载、保存和预览图像

转载 作者:行者123 更新时间:2023-12-01 10:58:24 25 4
gpt4 key购买 nike

我正在创建一个现代命令行应用程序,它接受命令并给出值,我已经创建了许多命令,我需要知道的是如何从互联网下载图像,将其保存在文件中,然后在 JOptionPane(JFrame) 上预览该图像,对于虚拟代码,我希望发生这种情况:

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

最佳答案

给定这个类,您(至少)有两种显示图像的方法:

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

关于java - 在 JOptionPane 上下载、保存和预览图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33482354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com