如何从数据库中读取图像数据并插入?

时间:2013-04-16 09:03:22

标签: c# asp.net

我希望你帮我解决一些误解错误。我实现了一个从活动目录获取所有内容的代码。问题是我不知道我是否正确实现了它,特别是图像数据。

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中的图像数据是“Varbinary(max)”。

这是动态网格视图:

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

除图像外的所有作品。你能帮忙或提供一些提示吗? 感谢。

2 个答案:

答案 0 :(得分:0)

将图像写入数据库

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

答案 1 :(得分:0)

您可以使用通用处理程序。

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

e.g。

public class ghCompanyLogoImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        Stream objLogoStream = null;

        objLogoStream = GetCompanyLogo(context);

        if (objLogoStream != null && objLogoStream.Length > 0)
        {
            // Set up the response settings
            context.Response.ContentType = "image/jpeg";
            context.Response.BufferOutput = false;

            const int buffersize = 1024 * 16;
            byte[] buffer = new byte[buffersize];
            int count = objLogoStream.Read(buffer, 0, buffersize);
            while (count > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, count);
                count = objLogoStream.Read(buffer, 0, buffersize);
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private Stream GetCompanyLogo(HttpContext context)
    {
        try
        {
            // Fetch image data stored in DB, convert it to MemoryStream and return it.
            // You can read querystring value here using "context.Request.QueryString[]"
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

然后,要以html显示图像,请将图片网址指定为

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

我希望它有所帮助。