How can I read image from URL in Java?

前端 未结 3 1076
萌比男神i
萌比男神i 2020-12-30 05:11

I have servlet in my web application that serves images, and when I visit those urls with browser images are server correctly. Then I have this other servlet that resizes im

3条回答
  •  一个人的身影
    2020-12-30 05:29

    Displays an image read from a URL within a JFrame. urlLocation URL pointing to an image.

    public class ShowImageFromURL {
    
        public static void show(String urlLocation) {
            Image image = null;
            try {
                URL url = new URL(urlLocation);
                URLConnection conn = url.openConnection();
                conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    
                conn.connect();
                InputStream urlStream = conn.getInputStream();
                image = ImageIO.read(urlStream);
    
                JFrame frame = new JFrame();
                JLabel lblimage = new JLabel(new ImageIcon(image));
                frame.getContentPane().add(lblimage, BorderLayout.CENTER);
                frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50);
                frame.setVisible(true);
    
            } catch (IOException e) {
                System.out.println("Something went wrong, sorry:" + e.toString());
                e.printStackTrace();
            }
        }
    }
    

    Ref: https://gist.github.com/aslamanver/92af3ac67406cfd116b7e4e177156926

提交回复
热议问题