這是.NET 4.0中的C#Winforms應用程序。如何在將字節數組轉換爲圖像時處理錯誤?
我從一個應該是JPG圖像的Web服務器接收一個字節數組。我這個數組轉換爲圖像如下:
// 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...
很多時候接收到的數據是不是某種類型的圖像,但垃圾。我真的更喜歡某種TryParse
的方法,因爲我明白通過使用異常捕獲來處理邏輯並不理想。
我該如何改進這種方法來乾淨地確定字節數組是否可以轉換爲圖像而不依賴於異常?
編輯:
基於的Mikael的回答,我現在檢查一個基本的「健康檢查」的前兩個字節試圖將圖像轉換之前。仍然可能有無效的數據流,但由於我通常會接收文本而不是圖像,因此標頭檢查將大大降低異常的頻率。
// 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...
這非常有用。它會通過做一些初步的完整性檢查來減少異常發生的次數(如果不是總是如此)。感謝您的建議! – JYelton 2010-09-16 18:03:18