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...