Getting a JPEG image from a hexadecimal string in XML

Well, I'm trying to assemble an image that is encoded as a hexadecimal string in an XML file. I was looking for answers to all this and could not find anywhere. Here is what I have.

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

return bmp2; 

The FilterResults function simply returns a string from XML. I can get the character string and convert it to byte [], but as soon as I execute Image.FromStream (mem), I get the "Invalid parameter" error.

Any ideas?

+3
source share
1 answer

The code snippet is correct (although it MemoryStreamimplements IDisposableand therefore should be wrapped in a block using).

Image.FromStream ArgumentException, . , - , , .

, , :

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);
    }
}
+3

Source: https://habr.com/ru/post/1739755/


All Articles