Here is a function that retrieves the size of an image directly into the file.
We just have to pass the file and its type parameter and return the size of the image as « Rectangle ».
//------------------------------------------------------------------------------------------------------
// AS3/AIR Extract Image size on file
// V 1.0
//------------------------------------------------------------------------------------------------------
public function GetImageSize(ImageFile : File, Type : String) : Rectangle {
var Result : Rectangle = new Rectangle(0,0,0,0);
var Bytes : ByteArray = new ByteArray();
var ImgStream : FileStream = new FileStream();
switch (Type){
case "bmp" :
Bytes.endian = Endian.LITTLE_ENDIAN;
break;
case "jpg" :
case "jpe" :
case "jpeg" :
case "png" :
case "gif" :
Bytes.endian = Endian.BIG_ENDIAN;
break;
}
ImgStream.open(ImageFile, FileMode.READ);
ImgStream.position = 0;
ImgStream.readBytes(Bytes, 0, ImgStream.bytesAvailable );
ImgStream.close();
Bytes.position = 0;
var ReadInt : uint = 0;
var ReadByte : uint = 0;
switch (Type){
case "jpg" :
case "jpe" :
case "jpeg" :
ReadInt = Bytes.readUnsignedShort();
if ( ReadInt == 0xFFD8 ){
while(Bytes.position < Bytes.length) {
ReadByte = Bytes.readUnsignedByte();
if(ReadByte == 0xFF) {
ReadByte = Bytes.readUnsignedByte();
if (ReadByte == 0xC0){
Bytes.readUnsignedShort(); // Skip section length
Bytes.readUnsignedByte(); // Skip bit depth
Result.height = Bytes.readUnsignedShort();
Result.width = Bytes.readUnsignedShort();
break;
}
}
}
}
return Result;
break;
case "bmp" :
Bytes.readUTFBytes(16);
Result.width = Bytes.readUnsignedInt();
Result.height = Bytes.readUnsignedInt();
break;
case "png" :
Bytes.readUTFBytes(16);
Result.width = Bytes.readUnsignedInt();
Result.height = Bytes.readUnsignedInt();
break;
case "gif" :
var SGTC : int = 0;
ReadInt = Bytes.readUnsignedInt();
if (ReadInt == 0x47494638 ) {
Bytes.readUnsignedShort(); // Skip 2 last chars '7a" or "9a"
Bytes.readUnsignedShort(); // Skip ScreenWidth
Bytes.readUnsignedShort(); // Skip ScreenHeight
var HeaderFlags : int = Bytes.readUnsignedByte(); // Get Flags
Bytes.readUnsignedByte(); // Skip Background Color Index
Bytes.readUnsignedByte(); // Skip Pixel Aspect Ratio
if ( (HeaderFlags & 0x1) > 0 ) {
HeaderFlags = (HeaderFlags >> 5 ) & 0x07 ;
SGTC = 3 * Math.pow(2,( HeaderFlags + 1));
if ( ( Bytes.position + SGTC ) < Bytes.length){
Bytes.position = Bytes.position + SGTC;
} else {
break;
}
}
while(Bytes.position < Bytes.length) {
ReadByte = Bytes.readUnsignedByte();
if ( ReadByte == 0x2C ){
Bytes.readUnsignedShort(); // Skip Left
Bytes.readUnsignedShort(); // Skip Top
Result.width = Bytes.readUnsignedByte() + 256 * Bytes.readUnsignedByte();
Result.height = Bytes.readUnsignedByte() + 256 * Bytes.readUnsignedByte();
break;
} else if ( ReadByte == 0x21 ){
while(Bytes.position < Bytes.length) {
ReadByte = Bytes.readUnsignedByte();
if ( ReadByte == 0x00 ) break; // Search Block Terminator
}
}
}
}
break;
}
return Result;
}
