Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A class for getting the width and height of a image file (gif or jpg) 1

Status
Not open for further replies.

petersJazz

Programmer
Jan 28, 2002
222
0
0
EU
Can I get the width and height of an image file (jpg or gif).

A class like this would be great:
Code:
GetSize gs = new GetSize(theFile);
int wid = gs.getWidth();
int hei = gs.getHeight();
 
There is no standard class to this, but it's actually fairly easy to write your own class to this.

All you need to do is get the specs for the different filetypes (bmp, gif, jpg, png) and locate the position of the height and width information in a file's structure.

For bmp generated with win95 & higher (integer, little endian):
width: bytes 19-22
height: bytes 23-26

For gif (short, little endian):
width: bytes 7+8
height: bytes 9+10

For png (integer, big endian):
width: bytes 17-20
height: bytes 21-24

For jpg (short, big endian) it gets a little more complicated; a jpg is set up of as a bunch of segments each segment has its own structure, meaning, and length. What you have to do is look for a segment which starts with 0xFFC0 and in that segment you'll find bytes 6+7 for height and 8+9 for width.

I'm currently implementing a class using this information, using the java.nio.ByteBuffer class for storage of the picture data.
 
If you create an ImageIcon object with the jpg or gif, you can use its getWidth() and getHeight() methods to get the size in pixels.
 
Thanks idarke,

it worked for jpg and gif files.

public void calcWidthHeight(String filename) {
ImageIcon ii = new ImageIcon(filename);
int width = ii.getIconWidth();
int height = ii.getIconHeight();
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top