Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从数据库中读取图像数据并将其插入?_C#_Asp.net - Fatal编程技术网

C# 如何从数据库中读取图像数据并将其插入?

C# 如何从数据库中读取图像数据并将其插入?,c#,asp.net,C#,Asp.net,我希望你能帮我纠正一些误解。我实现了一个从active directory获取所有内容的代码。问题是我不知道我是否正确地实现了它,尤其是图像数据 public System.Drawing.Image GetUserPicture(string userName) { try { var directoryEntry = new DirectoryEntry("LDAP://DC=darcairo,DC=com"); var directorySearcher = new D

我希望你能帮我纠正一些误解。我实现了一个从active directory获取所有内容的代码。问题是我不知道我是否正确地实现了它,尤其是图像数据

public System.Drawing.Image GetUserPicture(string userName) {
  try {
    var directoryEntry = new DirectoryEntry("LDAP://DC=darcairo,DC=com");
    var directorySearcher = new DirectorySearcher(directoryEntry);
    directorySearcher.Filter = ("(SamAccountName=" + userName + ")");
    var user = directorySearcher.FindOne();
    var bytes = user.Properties["thumbnailPhoto"][0] as byte[];
    using(var ms = new MemoryStream(bytes)) {
      return Bitmap.FromStream(ms);
    }
  } catch (Exception e) {
    return null;
  }
}
然后,我的目的是将这些数据(如用户名等)插入数据库

protected void Button1_Click(object sender, EventArgs e) {
  try {
    char[] delimiters = new char[] {
      '\\'
    };
    string domainuser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split(delimiters)[1];
    profile dir = new profile();
    string fname = dir.get_activeDiretory_DisplayName(domainuser);
    string mail = dir.get_activeDiretory_Email(domainuser);
    string department = dir.get_activeDiretory_Department(domainuser);
    string photo = Convert.ToString(dir.GetUserPicture(domainuser));
    string sql = string.Empty;
    string atc = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    sql = "INSERT INTO Profile (uid, uname, ufname, uemail, udepartment, uphoto) ";
    sql += "VALUES(@uid, @uname, @ufname, @uemail, @udepartment, @uphoto); set identity_insert Profile off";
    using(SqlConnection c = new SqlConnection(atc)) {
      using(SqlCommand cmd = new SqlCommand(sql, c)) {
        //cmd.Parameters.AddWithValue("OrderID", 1);
        cmd.Parameters.AddWithValue("uid", 1);
        cmd.Parameters.AddWithValue("uname", domainuser);
        cmd.Parameters.AddWithValue("ufname", fname);
        cmd.Parameters.AddWithValue("uemail", mail);
        cmd.Parameters.AddWithValue("udepartment", department);
        cmd.Parameters.AddWithValue("uphoto", photo);
        c.Open();
        cmd.ExecuteNonQuery();
        c.Close();
        Label2.Text = "Record Inserted";
      }
    }
    Label2.Text = "inserted";
  } catch (Exception s) {
    Label2.Text = "not inserted " + "Error= " + s.Message;
  }
  string str = "";
  foreach(GridViewRow g in GridView1.Rows) {
    str = str + g.Cells[0].Text + g.Cells[1].Text + g.Cells[2].Text + g.Cells[3].Text + g.Cells[4].Text + Convert.ToByte(g.Cells[5]);
  }
  GridView1.Enabled = true;
}
但是,sql中的图像数据是Varbinarymax

以下是动态栅格视图:

<asp:GridView 
  ID="GridView1" 
  runat="server" 
  AutoGenerateColumns="False" 
  BackColor="White" 
  BorderColor="#336666" 
  BorderStyle="Double" 
  BorderWidth="3px" 
  CellPadding="4" 
  DataKeyNames="UID" 
  DataSourceID="SqlDataSourceProf" 
  GridLines="Horizontal" 
  Width="433px" 
  Height="472px">
  <Columns>
    <asp:BoundField DataField="UID" HeaderText="UID" InsertVisible="False" ReadOnly="True" SortExpression="UID" />
    <asp:BoundField DataField="UName" HeaderText="UName" SortExpression="UName" />
    <asp:BoundField DataField="UFName" HeaderText="UFName" SortExpression="UFName" />
    <asp:BoundField DataField="UEmail" HeaderText="UEmail" SortExpression="UEmail" />
    <asp:BoundField DataField="UDepartment" HeaderText="UDepartment" SortExpression="UDepartment" />
    <asp:TemplateField>
      <ItemTemplate>
        <asp:Image ID="Image1" Height="100" Width="100" runat="server" ImageUrl='' />
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
  <FooterStyle BackColor="White" ForeColor="#333333" />
  <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
  <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
  <RowStyle BackColor="White" ForeColor="#333333" />
  <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
  <SortedAscendingCellStyle BackColor="#F7F7F7" />
  <SortedAscendingHeaderStyle BackColor="#487575" />
  <SortedDescendingCellStyle BackColor="#E5E5E5" />
  <SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<asp:SqlDataSource 
  ID="SqlDataSourceProf" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
  SelectCommand="SELECT * FROM [Profile]">
</asp:SqlDataSource>
除图像外,所有作品均有效。你能帮我一下或给我一些提示吗?
谢谢。

正在将图像写入数据库

public static void WriteImage(ref SqlCommand CMD, Bitmap Img, string ParaName)
{
    WriteImage(ref CMD, Img, ParaName, SupportedImageFormats.JPG);
}


public static void WriteImage(ref SqlCommand CMD, Bitmap Img, string ParaName, SupportedImageFormats imgFormat)
{
    using (System.IO.MemoryStream MS = new System.IO.MemoryStream()) {
        SaveToStream(MS, Img, imgFormat, false);
        CMD.Parameters.Add(ParaName, SqlDbType.VarBinary).Value = MS.GetBuffer();
    }
}
对于位图对象

Bitmap mImage = new Bitmap(strPathForImage);

您可以为此使用通用处理程序

将用户id作为查询字符串参数传递给泛型处理程序,将处理程序响应类型设置为image/jpg,并将图像数据写入响应。然后将此处理程序指定为ImageUrl

e、 g

然后,要在html中显示图像,请将图像url指定为

ImageUrl ="~/ghCompanyLogoImage.ashx?ID=Val"

我希望这会有所帮助。

与其干预文件流,为什么不将图片保存到服务器,然后只在数据库中存储路径?将图像转换为字节数据,然后将块添加到命令,
ImageUrl ="~/ghCompanyLogoImage.ashx?ID=Val"