Checking in Flex/AS3 for corrupt JPGs (invalid images)

-

February 25th, 2010

by Bryce Barrand

In a recent project we were running into problems with corrupt jpg images that end users were uploading. We wanted to check on the Flex side if these images were invalid before even uploading them. (We do check for image validity on the server side as well, but why waste the upload time?)

Here is a function that will take in the byte array for a jpg and tell you if it is valid or not. Keep in mind this doesn’t check everything, just that we have a file that has the correct EOI segment header at the end.

Update 3/24/10: I added one more sequence of valid bytes

protected function isValid(bytes:ByteArray):Boolean
{
	var toReturn:Boolean = false;
 
	//take the file name and check it against jpg extensions to make sure it is a jpg
	var namePieces:Array = file.name.split(".");
	//I'm getting the file extension this lame way, bc for some reason file.type is null
	var extension:String = namePieces[namePieces.length -1];
 
	//if it is indeed a jpeg then we want to check the validity
	if(extension.toLowerCase() == 'jpg' || extension.toLowerCase() == 'jpeg')
	{
		//move to the second to last position in the bytearray
		bytes.position = bytes.bytesAvailable - 2;
 
		//get the last two bytes
		var secondToLastByte:uint = bytes.readUnsignedByte();
		var lastByte:uint = bytes.readUnsignedByte();
 
		//if the last two bytes don't match the EOI segment header at the end of the file
		//then we know it is invalid
 
		if((secondToLastByte == 255 && lastByte == 217) || (secondToLastByte == 217 && lastByte == 0))
		{
			toReturn = true;
		}
	}
	else
	{
		toReturn = true;
	}
 
	return toReturn;
}

Inspiration for this bit of code came from http://stackoverflow.com/questions/198438/efficiently-detect-corrupted-jpeg-file

Leave a Reply

CAPTCHA Image CAPTCHA Audio
Refresh Image