• 在Gridview中显示数据库中的二进制图片
  • 发布于 2个月前
  • 177 热度
    0 评论
  • 雷布斯
  • 0 粉丝 38 篇博客
  •   

我们在用.NET开发系统时,经常会用到在Gridview控件中显示图片的功能,很多时候,我们都是把图片以二进制的形式保存在数据库中的。那如果要在Gridview中直接显示二进制中的图片该怎么实现呢?我这会介绍两种方式1.使用 ashx方式从后台读取数据并显示 2.用base64 。

具体看如下例子:

1.前台页面

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID"  />
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
                <asp:TemplateField HeaderText=" show images using ashx">
                    <ItemTemplate>
                        <img  src ='/Services/WriteImages.ashx?id=<%# Eval("CategoryID")  %>' />
                    </ItemTemplate>
                    
                </asp:TemplateField>
                <asp:TemplateField HeaderText=" show images using base64">
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server"  />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [CategoryID], [CategoryName], [Description],[image] FROM [Categories]"></asp:SqlDataSource>


2.把二进制数据转换成base64格式显示的实现方式

在Gridview的RowDataBound事件中把二进制数据转换成base64的格式显示,代码如下:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // get the data of the row if you bind data with datatable
                // if you use List<YourModel> as DataSource , you should use as YourModel
                DataRowView view = e.Row.DataItem as DataRowView;
                // get the base64 string of the byte data
                string base64 = Convert.ToBase64String(view[3] as byte[]);
                Image image = e.Row.FindControl("Image1") as Image;
                // set the image's src to base64 string
                image.ImageUrl = "data:image/png;base64," + base64;
            }
        
         }


3.用ashx实现的方式

public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["Id"] != null)
            {

                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
                {
                    // get the id of the category to get the category's image data
                    SqlCommand cmd = new SqlCommand("SELECT image,categoryName FROM [Categories]  WHERE CategoryId = @Id", con);
                    cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(context.Request.QueryString["Id"]));
                    con.Open();
                    SqlDataReader sdr = cmd.ExecuteReader();
                    if (sdr.Read())
                    {

                        context.Response.Buffer = true;
                        context.Response.Charset = "";
                        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        context.Response.ContentType = "img/jpeg";
                              // write back the byte data of image then the image will show 
                        context.Response.BinaryWrite((byte[])sdr["image"]);
                        con.Close();
                        context.Response.Flush();
                        context.Response.End();
                    }

                }
            }

两种方式你可以任选一种,都可以实现在gridview中显示数据库中的二进制图片的功能,具体效果如下:

用户评论