Source

image-measure / src / samplomat / ImageMeasure.as

package samplomat
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Rectangle;
	
	// http://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java
	public class ImageMeasure implements IEventDispatcher
	{
		public function ImageMeasure()
		{
		}
		
		public function jpeg(file : File) : Rectangle
		{
			var dimensions : Rectangle;
			var marker : int;
			var length : int;
			var width : Number, height : Number;
			var stream : FileStream = new FileStream();
				stream.open(file, FileMode.READ);
				
			if(stream.readUnsignedByte() != 0xFF || stream.readUnsignedByte() != 0xD8) {
				throw new Error("Not a jpeg file.");
			}
			
			while(stream.readUnsignedByte() == 0xFF)
			{
				marker = stream.readUnsignedByte();
				length = stream.readUnsignedByte() | stream.readUnsignedByte();
				
				if(marker == 0xC0)
				{
					stream.readUnsignedByte();
					height = stream.readUnsignedByte() << 8 | stream.readUnsignedByte();
					width = stream.readUnsignedByte() << 8 | stream.readUnsignedByte();
					dimensions = new Rectangle(0, 0, width, height);
					break;
				}
				
				stream.position += (length) - 2;
			}
			
			stream.close();
			
			return dimensions;
		}
		
		public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
		{
		}
		
		public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void
		{
		}
		
		public function dispatchEvent(event:Event):Boolean
		{
			return false;
		}
		
		public function hasEventListener(type:String):Boolean
		{
			return false;
		}
		
		public function willTrigger(type:String):Boolean
		{
			return false;
		}
	}
}