开发者

How do I handle errors when converting a byte array to image?

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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜