Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Image Width and Height in Java

I just want to ask how to get the width and height of an image, because this returns -1 for width and height:

private void resizeImage(Image image){
    JLabel imageLabel = new JLabel();

    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    System.out.println("Width:" + imageWidth);
    System.out.println("Height:" + imageHeight);
}
like image 994
Dannika Rodriguez Avatar asked Sep 25 '26 20:09

Dannika Rodriguez


2 Answers

You should do something like this :

BufferedImage bimg = ImageIO.read(new File(filename));
int width          = bimg.getWidth();
int height         = bimg.getHeight(); 

as this post says

like image 99
Abstract Avatar answered Sep 27 '26 10:09

Abstract


With Apache Commons Imaging, you can get image width and height with better performance, without reading entire image to memory.

Sample code below is using Sanselan 0.97-incubator (Commons Imaging is still SNAPSHOT as I write this):

final ImageInfo imageInfo = Sanselan.getImageInfo(imageData);
int imgWidth = imageInfo.getWidth();
int imgHeight = imageInfo.getHeight();
like image 36
Hendy Irawan Avatar answered Sep 27 '26 10:09

Hendy Irawan