1

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

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>

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

4

2 回答 2

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);
于 2013-04-16T09:39:40.827 回答
0

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

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

例如

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 中显示图像,请将图像 url 指定为,

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

我希望它有所帮助。

于 2013-04-16T10:05:31.960 回答