How to convert an SQL Server BLOB string to System.Drawing.Image?

时间秒杀一切 提交于 2019-12-06 15:28:16
pdriegen

The issue is that the conversion between the hex-encoded string to byte array isn't being done property.

The code you listed will treat each of the chars in the blob as a byte, so an 'F' will be treated as 0x46 (the ascii code for a capital F). What you want to do is de-code each 2 characters as a single byte - i.e. F0 = 240 etc.

It assumes the string is an even number of characters. You'll also need to strip off the '0x' prefix, as that's just an indicator that what follows is a hexadecimal representation of the data.

So instead of this:

strPhoto = csvuser.photo; // The string that represents the BLOB
byte[] bytes = new byte[strPhoto.Length * sizeof(char)];
System.Buffer.BlockCopy(strPhoto.ToCharArray(), 0, bytes, 0, bytes.Length);

Do something like this (adapted from previous answer given here):

      strPhoto = csvuser.photo; // The string that represents the BLOB

      //remove first 2 chars (the '0x')
      strPhoto = strPhoto.Remove(0, 2);

      //convert hex-string to bytes:
      int NumberChars = strPhoto.Length/2;
      byte[] bytes = new byte[NumberChars];
      using (StringReader sr = new StringReader(strPhoto)){
            for (int i = 0; i < NumberChars; i++)
               bytes[i] = Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
      }

      // Then we create a memory stream that holds the image
      MemoryStream photostream = new MemoryStream( bytes );

      // Then we can create a System.Drawing.Image by using the Memory stream
      var photo = Image.FromStream(photostream);

Do this to convert your string to byte[]:

System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(strPhoto);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!