Getting Image from URL (Java)

前端 未结 6 2079
长发绾君心
长发绾君心 2020-12-10 01:09

I am trying to read the following image

\"enter

But it is showing IIOException

6条回答
  •  我在风中等你
    2020-12-10 01:54

    Try:

    public class ImageComponent extends JComponent {
      private final BufferedImage img;
    
      public ImageComponent(URL url) throws IOException {
        img = ImageIO.read(url);
        setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
    
      }
    
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
      }
    
      public static void main(String[] args) throws Exception {
        final URL kitten = new URL("https://placekitten.com/g/200/300");
    
        final ImageComponent image = new ImageComponent(kitten);
    
        JFrame frame = new JFrame("Test");
        frame.add(new JScrollPane(image));
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
      }
    }
    

提交回复
热议问题