Getting JPG dimensions with AS3 without loading the entire file
Does this sound familiar: You’re loading a JPG file, and want to know what size it is before it has loaded? This can be useful if you’re for example drawing a border/background, which will contain the image. If you don’t know what size the image is, you don’t know what size the box should be. I’m sure there are better & more common uses to this, but i know for sure it can be really useful.
Anyway, I decided to solve this problem. If you don’t care about how it works, fine, i’ll give you the short version first. After all the class i’ve created does all the heavy lifting for you, so if you just want to have it work, you can just use it without worrying about what’s under the hood.
Here’s the class: JPGSizeExtractor.as. Download it and put it in a folder com/anttikupila/utils in your classpath. Then you can just use it like this:
- var je : JPGSizeExtractor = new JPGSizeExtractor( );
- je.addEventListener( JPGSizeExtractor.PARSE_COMPLETE, sizeHandler );
- je.extractSize( your_jpg_file.jpg );
- function sizeHandler( e : Event ) : void {
- trace( "Dimensions: " + je.width + " x " + je.height );
- }
To trace out debug information, you can say je.debug = true;
What it actually does is that it starts loading the JPG file and analyzes every byte that has loaded. When it find the jpg’s JFIF headers (according to the JPEG specs), it will be able to determine the dimension of the file and close the stream. The dimensions in a jpg are before the actual image info, meaning that you can load a 10mb file and get it’s dimensions in a fraction of a second, instead of waiting for the entire file to load.
Note: This doesn’t work for all files. Some files i tried with were not according to the JPEG specs (or then i misunderstood something, which is more likely since other software showed the correct dimensions). Don’t use this in mission critical projects, unless you have control over the JPG files. I don’t take any responsibility of it working correctly.
Download the class, with an example
If you’re not so much interested in “the whatâ€, but more “the howâ€? Read on. Let’s see what we can do about that ..