无法使用C#从SQL Server读取图像

时间:2017-01-19 18:19:21

标签: c# sql-server

当我尝试从SQL Server数据库中读取图像时,出现错误:在以下行中:

Sub MakeArrayInDropDown()
    ' Declare variables
    Dim i As Integer            ' Counter for-loop
    Dim i_lastStr As Integer    ' Length of strings in column A
    Dim wb As Workbook          ' Short workbookname
    Dim ws As Worksheet         ' Short worksheet name
    Dim TC As Range             ' Target Cell (TC)
    Dim DD As Shape             ' Dropdown shape
    ' Set workbook and worksheet
    Set wb = ThisWorkbook
    Set ws = ActiveSheet

    ' Set cell where all unique strings should go to
    Set TC = ws.Cells(1, 3)

    ' Determine amount of strings in column A
    i_lastStr = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    ' Add Form Control dropdown to target cell
    Set DD = ws.DropDowns.Add(TC.Left, TC.Top, TC.Width, TC.Height)
    DD.Name = "dropdown_row" & TC.Row
    DD.AddItem ""  'Adds a blank entry in the first row of the dropdown
    DD.AddItem ws.Cells(i,1).Value
    For i = 2 To i_lastStr
        ' Add if next string is different from the string previously added
        ElseIf Not StrComp(ws.Cells(i-1, 1), ws.Cells(i, 1)) = 0 Then
            DD.AddItem ws.Cells(i, 1).Value
        End If
    Next i

End Sub
  

System.Drawing.dll中出现未处理的“System.ArgumentException”类型异常

     

附加信息:参数无效。

我的代码:

Image returnImage = Image.FromStream(ms);

2 个答案:

答案 0 :(得分:0)

使用SqlDataReader.GetStream方法。

所以你会做一些事情:

using(SqlDataReader imageReader = selectSingleImageCommand.ExecuteReader(CommandBehavior.SequentialAccess))
{
    if (imageReader.Read())
    {
        using (Stream backendStream = imageReader.GetStream(0))
        {
            //Do whater you need with the Stream
        }
    }   
}

你也可以迭代阅读器(选择多个图像)并按流打开 - 我没有那样使用它,所以我不是百分百肯定。

答案 1 :(得分:-1)

  try
    {
        SqlCommand cmdSelect=new SqlCommand("select Picture" + 
              " from tblImgData where ID=@ID",this.sqlConnection1);
        cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
        cmdSelect.Parameters["@ID"].Value=this.editID.Text;

        this.sqlConnection1.Open();
        byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();
        string strfn=Convert.ToString(DateTime.Now.ToFileTime());
        FileStream fs=new FileStream(strfn, 
                          FileMode.CreateNew, FileAccess.Write);
        fs.Write(barrImg,0,barrImg.Length);
        fs.Flush();
        fs.Close();
        pictureBox1.Image=Image.FromFile(strfn);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        this.sqlConnection1.Close();
    }