Skip to main content

APIzation: Replication Package

[Q#8184040][A#8184129] How can I get height and width of an image?

https://stackoverflow.com/q/8184040

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?

Answer

https://stackoverflow.com/a/8184129

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.

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

APIzation

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);
            }
        });
    }
}
package com.stackoverflow.api;

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

public class Human8184129 {

  public static void printImageHeighthAndWidth(URL url) {
    BufferedImage bi = ImageIO.read(url);
    String size = bi.getWidth() + "x" + bi.getHeight();
    SwingUtilities.invokeLater(
      new Runnable() {
        @Override
        public void run() {
          JLabel l = new JLabel(size, new ImageIcon(bi), SwingConstants.RIGHT);
          JOptionPane.showMessageDialog(null, l);
        }
      }
    );
  }
}

package com.stackoverflow.api;

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

/**
 * How can I get height and width of an image?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/8184129">https://stackoverflow.com/a/8184129</a>
 */
public class APIzator8184129 {

  public static void getHeight(String str1) throws Exception {
    URL url = new URL(str1);
    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);
        }
      }
    );
  }
}