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

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.bytesAvailable2;
      
      //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

By: Bryce Barrand Categories: Blogroll

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>