Search code examples
c#imagememorystreamvarbinary

How do I convert a VarBinary Value to an image?


I have a Table in my database like so:

Id  |  Description  | Icon

where the Icon column is of type varbinary(max)

I have a row in this table where the value in the Icon column is shown in the pastebin link (because it is a long value):

http://pastebin.com/LbVAf20A

I am trying to convert this varbinary value to an Image in my program using the following code mentioned here:

var binary = new System.Data.Linq.Binary(GetBytes(StreamText)).ToArray();
using (MemoryStream stream = new MemoryStream(binary))
{
    var image = new System.Drawing.Bitmap(stream);
    image.Save(DownloadPath, ImageFormat.Png);
}

private byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
}

Where StreamText is the string in the pastebin link

But at the row var image... I keep getting the exception.

Parameter is not valid

What am I doing wrong?


Solution

  • Problem is your string is hex string, and you trying to convert it to byte array as if it was ascii string. You can use any method you can find around internet to convert your hex string to byte array, like this:

        static void Main(string[] args)
        {
            var s = "your long hex string";
            if (s.StartsWith("0x"))
                s = s.Remove(0, 2);
            using (var stream = new MemoryStream(ConvertHexStringToByteArray(s)))
            {
                var image = new Bitmap(stream);
                image.Save(DownloadPath, ImageFormat.Png);
            }            
        }
    
        public static byte[] ConvertHexStringToByteArray(string hexString) {
            if (hexString.Length%2 != 0) {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
            }
    
            byte[] HexAsBytes = new byte[hexString.Length/2];
            for (int index = 0; index < HexAsBytes.Length; index++) {
                string byteValue = hexString.Substring(index*2, 2);
                HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            }
    
            return HexAsBytes;
        }