开发者

How to check if MemoryStream can convert to Bitmap in .NET?

As the question mentioned, I have a memorystream from a Byte[] ByteArr. How can I check if it can convert to a bitmap before using it with Bitmap myImg = new Bitmap(memorystream).

开发者_Python百科

Update Problem: In my situation, I load an Image from Internet through a URL, then if the Img downloaded already I change bitmap to base64string, if not download I change url to base64string. And then I save in xml file. Next time I load from XML and change base64String to byte[], then byte[] can be a string or a bitmap. So I want to detect which type my memorystream from byte[] be (Image or String) before converting it.


.NET supports lots of image file formats. You can't reasonably screen the memory stream content for all possible formats. Looking for the cookie in the image header isn't enough, the image might still not load if there's something wrong with the image data or the image happens to be stored in a format that the .NET decoder doesn't support.

Punt this: just load the image. If there's something wrong with it, you'll get a loud complaint. Catch the exception.


My understanding of bitmap is that it is an extremely simple format - no compression, etc. There are some headers, and the rest is pixels RGB values. So, most memory streams should be valid as BMPs, but if they do not - you would get an exception. I say it is ok to try to convert it and get an exception or an error code if it is malformed.

http://en.wikipedia.org/wiki/BMP_file_format


Check if the first byte is 0x42. If it is not, then it is not a bitmap. If it is, then pass it to the Bitmap constructor and catch any exceptions to look for cases where the 0x42 was a false positive.


Actually, wiki is your friend. Check out the BMP File Header section for some info: BMP File Format

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜