开发者

Getting a JPEG image from a hex string in XML

Well here goes, I am trying to collect a picture that is encoded as a hex string in an xml file. I have been looking all over for the answer to this and have not been able to find it any where. Here is what I have now.

byte[] bytes = Convert.FromBase64String(FilterResults("PHOTOGRAPH"));
MemoryStream mem = new MemoryStream(bytes);
Image bmp2 = Image.FromStream(mem);

return bmp2;开发者_JAVA百科 

The FilterResults function just returns the string from the XML. I am able to get the string of characters and convert it into a byte[] but as soon as I execute the Image.FromStream(mem) I get an "Parameter Incorrect" error.

Any ideas?


The code snippet is correct (although MemoryStream implements IDisposable and should therefore be wrapped in a using block).

Image.FromStream only throws an ArgumentException if it doesn't recognize the image format in the stream. So unless there's some code you're not showing, then the problem has to be with the image itself.

To satisfy yourself that the code is correct, use the following test program on an actual image file sitting on your hard drive somewhere:

string imageBase64;
using (Image image = Image.FromFile(@"C:\path_to_image.jpg"))
{
    using (MemoryStream ms = new MemoryStream())
    {
        image.Save(ms, ImageFormat.Jpeg);
        imageBase64 = Convert.ToBase64String(ms.ToArray());
    }
}
Console.WriteLine(imageBase64.Length);

byte[] imageData = Convert.FromBase64String(imageBase64);
using (MemoryStream ms = new MemoryStream(imageData))
{
    using (Image image = Image.FromStream(ms))
    {
        Console.WriteLine(image.Width);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜