2016-09-19 203 views
1

我有一個表在我的數據庫如下所示:如何將VarBinary值轉換爲圖像?

Id | Description | Icon 

其中Icon列的類型的varbinary(max)

我在這個表中的一行,其中在Icon列中的值在引擎收錄中示出鏈接(因爲它是一個長期的值):

http://pastebin.com/LbVAf20A

我想這VARBINARY值轉換爲圖像在我的計劃採用t他下面的代碼中提到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; 
} 

StreamText是在引擎收錄鏈接

繩子,但在該行var image...我不斷收到異常。

參數無效

我在做什麼錯?

+2

爲什麼你讓你的varbinary列從數據庫中的字符串,而不是直接字節數組? – Evk

+0

@Evk爲方便起見,我正在複製並粘貼varbinary列的'string'值,並希望將其轉換爲圖像。如果我直接得到了值,我將需要更多的UI來讓用戶選擇一個表格,並且行 – user1

+1

@ user1從什麼複製和粘貼? – juharr

回答

1

問題是您的字符串是十六進制字符串,並且您試圖將它轉換爲字節數組,就好像它是ascii字符串一樣。你可以使用你可以找到各地的互聯網,將十六進制字符串轉換爲字節數組,任何這樣的方法:

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; 
    }