How can I get height and width of an image?

前端 未结 5 1020
野的像风
野的像风 2021-01-04 19:40

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          


        
5条回答
  •  悲哀的现实
    2021-01-04 19:48

    You want something like this:

        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
            Image image = ImageIO.read(url);
    
            System.out.println("Height: " + image.getHeight(null));
    
    
        }
        catch(MalformedURLException e) {
            e.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    

    The java.awt.Toolkit approach won't block, so will return -1 and notify the observer (or not in your case because it's null) when it is loaded. If you do want it asynchronously then you'll need to provide a callback in the form of an image observer.

    Oh, and don't just ignore exceptions, at least print the stack trace!

提交回复
热议问题