【问题标题】:How do I convert a VarBinary Value to an image?如何将 VarBinary 值转换为图像?
【发布时间】:2016-09-19 11:46:35
【问题描述】:

我的数据库中有一个表格,如下所示:

Id  |  Description  | Icon

Icon 列的类型为 varbinary(max)

我在此表中有一行,其中 Icon 列中的值显示在 pastebin 链接中(因为它是一个长值):

http://pastebin.com/LbVAf20A

我正在尝试使用here 提到的以下代码在我的程序中将此 varbinary 值转换为图像:

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 是 pastebin 链接中的字符串

但在var image... 行,我不断收到异常。

参数无效

我做错了什么?

【问题讨论】:

  • 为什么你的 varbinary 列作为字符串从数据库中获取,而不是直接作为字节数组?
  • @Evk 为方便起见,我正在复制并粘贴我的 varbinary 列的 string 值,并且只想将其转换为图像。如果我直接得到值,我需要更多的 UI 让用户选择一个表和行
  • @user1 从什么复制粘贴?
  • @Juharr 登录 Sqlserver,使用 Select * from table 查看表并复制并粘贴 Icon 列的值

标签: c# image memorystream varbinary


【解决方案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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多