本文介绍了如何图像转换为BufferedImage的在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

如何转换来的在Java中?

How to convert Image to BufferedImage in Java?

请注意,这显然是不正确的,因为它使用的方法 的getWidth(空)的getHeight(空) ,它可以返回 1 ,如果图像是不尚未加载(图片,顾名思义,异步对象)。

Note, that existing answer is apparently not correct, because it uses methods getWidth(null) and getHeight(null), which can return -1 if image is not loaded yet (Image is, by definition, an asynchronous object).

请,请提供更正确的答案,以上证明,现有的答案已经是正确的。

Please, provide either more correct answer, or more proofs that existing answer is already correct.

推荐答案

如果这对你很重要,你可以使用媒体跟踪​​来等待的形象是加载,那么你并不需要关心提供一个的ImageObserver

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

我不希望添加任何图形用户界面,我只需要下载图片或失败

好吧,如果你需要下载的形象,那么你可以只用 ImageIO.read(URL),看一看的了解更多详情...那么你就不会需要关心关于图片媒体跟踪​​,因为的ImageIO 返回的BufferedImage

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

这篇关于如何图像转换为BufferedImage的在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:25