SqlDataReader:将varbinary读入字节数组

时间:2018-07-08 09:24:10

标签: c# sqldatareader varbinary varbinarymax

我有一个带有varbinary(max)列的SQL Server表。我用它来存储图像。用OpenFileDialog选择图像,像这样翻译成byte[]

public byte[] ConvertImageToByteArray(String filepath)
{
    try
    {
        return File.ReadAllBytes(filepath);
    }
    catch (Exception) 
    {
        throw; 
    }
}

,然后使用以下代码行将其存储到数据库中:

sqlCmd.Parameters.Add("@image", SqlDbType.VarBinary).Value = image;

它看起来像这样存储在数据库中,所以我想一切似乎都按预期运行。

enter image description here

很遗憾,我无法从数据表中加载图像。

我正在使用SqlDataReader来这样做:

DbSql db = new DbSql();

SqlDataReader dr = db.GetDataReader(sqlCmd);

if (dr.Read())
{
    if (!dr.IsDBNull(1))
        productName = dr.GetString(1);

    if (!dr.IsDBNull(2))
        identNumber = dr.GetString(2);

    [...]

    if (!dr.IsDBNull(23))
        comment = dr.GetString(23);

    if (!dr.IsDBNull(24))
    {
        byte[] image = dr.GetSqlBytes(24).Value;  // <- This is where I try to grab the image
    }
}

似乎我无法使用

创建合适的byte[]
image = dr.GetSqlBytes(24).Value;

因为我的下一步无法再次将其变成图片:

public Image ConvertImageFromByteArray(byte[] array)
{
        try
        {
            MemoryStream ms = new MemoryStream(array);
            return Image.FromStream(ms);
        }
        catch (Exception) { throw; }
    }

编辑: 当尝试类似的东西     pictureBox.Image = ConvertImageFromByteArray(image) 我收到一条错误消息:“参数无效”(自行翻译,德语为“UngültigerParameter”) enter image description here

任何人都可以提供解决方案吗?

1 个答案:

答案 0 :(得分:1)

一旦将varbinary(MAX)转换为字节数组

image = (byte[])dr[24];

尝试一下。

    MemoryStream ms = new MemoryStream(image);
    imagePictureBox.Image = System.Drawing.Image.FromStream(ms);

这就是我创建字节数组的方式...

    if (File.Exists(sLogoName) == false)
       throw new Exception("File Not Found: " + sLogoName);
    FileStream sourceStream = new FileStream(sLogoName, FileMode.Open, FileAccess.Read);
    int streamLength = (int)sourceStream.Length;
    Byte[] byLogo = new Byte[streamLength];
    sourceStream.Read(byLogo, 0, streamLength);
    sourceStream.Close();
相关问题