Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get height and width of an image?

Why is the following bit of code returns Height: -1 which means that the height is yet not known. How to get height of the image?

 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) {
    }
like image 580
Radek Avatar asked Nov 18 '11 14:11

Radek


1 Answers

Use ImageIO.read(URL) or ImageIO.read(File) instead. It will block while loading, and the image width & height will be known after it returns.

E.G.

enter image description here

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);
            }
        });
    }
}

Alternately, add a MediaTracker to the image being loaded asynchronously by the Toolkit and wait until it is completely loaded.

like image 127
Andrew Thompson Avatar answered Oct 01 '22 23:10

Andrew Thompson