tangguo

如何获得图像的高度和宽度?

java

为什么下面的代码返回高度:-1,这意味着高度未知。如何获得图像的高度?

 try {
        // Create a URL for the image's location
        URL url = new URL("http://bmw-2006.auto-one.co.uk/wp-content/uploads/bmw-m3-2006-3.jpg");

        // Get the image
        java.awt.Image image = Toolkit.getDefaultToolkit().createImage(url);

        System.out.println("Height: " + image.getHeight(null));


    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }

阅读 359

收藏
2020-11-20

共1个答案

小编典典

使用ImageIO.read(URL)或ImageIO.read(File)代替。加载时它将阻塞,返回后将知道图像的宽度和高度。

例如

import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;

class SizeOfImage {

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
        final BufferedImage bi = ImageIO.read(url);
        final String size = bi.getWidth() + "x" + bi.getHeight();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JLabel l = new JLabel( 
                    size, 
                    new ImageIcon(bi), 
                    SwingConstants.RIGHT );
                JOptionPane.showMessageDialog(null, l);
            }
        });
    }
}

或者,MediaTracker向由异步加载的映像中添加A ,Toolkit然后等待其完全加载。

2020-11-20