How to convert Image to BufferedImage in Java?

前端 未结 1 1234
旧时难觅i
旧时难觅i 2020-12-21 21:50

How to convert Image to BufferedImage in Java?

Note, that existing answer is apparently not correct, because it uses methods getWidth(null) and getHeight(null), whic

相关标签:
1条回答
  • 2020-12-21 22:14

    If it's important to you, you can use a MediaTracker to "wait" for the image to be loaded, then you don't need to care about supplying a ImageObserver

    try {
        MediaTracker mt = new MediaTracker(new JPanel());
        Image image = Toolkit.getDefaultToolkit().createImage("...");
        mt.addImage(image, 0);
        System.out.println("Wait for...");
        mt.waitForAll();
        System.out.println("I be loaded");
    
        BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    

    Have a look at MediaTracker JavaDocs for more details

    I don't wish to add any GUI, I just need to download image or fail

    Okay, if you "need to download" the image, then you can just use ImageIO.read(URL), have a look at Reading/Loading an Image for more details ... then you won't need to care about Image or MediaTracker, as ImageIO returns a BufferedImage

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