views:

18

answers:

3

This is a C# Winforms App in .NET 4.0.

I receive a byte array from a web server which is supposed to be a JPG image. I convert this array to an image as follows:

// byte[] ImageData ...
bool ValidImage = false;
try
{
    MemoryStream ms = new MemoryStream(ImageData);
    Bitmap FinalImage = new Bitmap(ms);
    ValidImage = true;
}
catch (ArgumentException)
{
    ImageStatus = "Invalid";
}
if (ValidImage) // do stuff...

Very often the data received is not an image but garbage of some sort. I really would prefer some sort of TryParse approach, as I understand handling logic by using exception catching to be less than desirable.

How can I improve this method to cleanly determine if a byte array can be converted to an image without relying on an exception?

EDIT:

Based on Mikael's answer, I am now checking the first two bytes for a rudimentary "sanity check" before attempting to convert the image. It's still possible to have an invalid data stream, but since I usually receive text instead of an image, the header check will greatly reduce the frequency of the exception.

// byte[] ImageData ...
bool ValidImage = false;
try
{
    if (ImageData[0] == 0xFF && ImageData[1] == 0xD8)
    {
        MemoryStream ms = new MemoryStream(ImageData);
        Bitmap FinalImage = new Bitmap(ms);
        ValidImage = true;
    }
}
catch (ArgumentException)
{
    ImageStatus = "Invalid";
}
if (ValidImage) // do stuff...
+1  A: 

You can't, at least not without some significant work. There is no Bitmap.TryParse.

You could look at the headers of the byte data and see if it looks like a JPG. But even then it's possible to receive garbage.

I recommend sticking with your current approach.

Judah Himango
Looking at the headers will help cut down on how frequently I need to rely on the exception. The exception handler of course will remain but some preliminary checking is ideal.
JYelton
+1  A: 

You could check the first bytes to validate the header at least.

byte 1-2: 0xFFD8

byte 3-4: pixel width

byte 5-6: pixel height

if these are sensible you are on your way.

As for using an exception to handle the errors, I don't think it should be a problem. You're only handling the particular error, and for a reason.

Mikael Svenson
@Mikael Svenson: This is extremely useful. It will cut down on the number of times the exception occurs (if not always) by doing a little preliminary sanity checking. Thanks for the suggestion!
JYelton
A: 

Your code looks fine. You assume that the bytes are a valid image, so if they're not then the situation is truly 'exceptional'...

Visage