How can I read image from URL in Java?

前端 未结 3 1054
萌比男神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

    0 讨论(0)
  • 2020-12-30 05:35
    URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
    Image image = ImageIO.read(url);  
    

    or

    URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
    java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(url);   
    

    Update:

    This code works for me Try checking your URL.

    public static void main(String[] args) throws Exception {
       URL imageURL = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
        // Case 1
        RenderedImage img = ImageIO.read(imageURL);
        System.out.println(img);
    }
    

    output:

    BufferedImage@e80a59: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 col
    or space = java.awt.color.ICC_ColorSpace@1ff5ea7 transparency = 1 has alpha = fa
    lse isAlphaPre = false ByteInterleavedRaster: width = 553 height = 737 #numDataE
    lements 3 dataOff[0] = 2
    
    0 讨论(0)
  • 2020-12-30 05:36

    From the docs:

    If no registered ImageReader claims to be able to read the resulting stream, null is returned.

    Could it be that you have no registered ImageReader for the image type?

    0 讨论(0)
提交回复
热议问题