ASP.NET将二进制映像绑定到转发器中的映像控制

时间:2016-10-12 11:00:39

标签: c# asp.net

我有一个像这样的简单转发器:

<asp:Repeater ID="repImages" runat="server" OnItemDataBound="repImages_ItemDataBound">
        <ItemTemplate>
            <asp:Image ID="Image1" runat="server" />
        </ItemTemplate>
    </asp:Repeater>

像这样的数据绑定:

void BindImages()
    {
        string sql = @"SELECT A.*, B.* FROM ImageMetaData A
INNER JOIN ImageData B
ON A.ImageId = B.ImageId
WHERE A.CapId = @capid AND width = 250";
        SqlQuery q = new SqlQuery("imagelibrary", sql);
        q.Parameters.AddWithValue("@capid", Convert.ToInt32(ddlVehicle.SelectedValue));
        DataTable dt = q.OpenDataTable();
        repImages.DataSource = dt;
        repImages.DataBind();
    }

我绑定的数据表有一个字段,其中包含一个图像作为字节数组。如何让图像控件显示:

 protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Image img = (Image)e.Item.FindControl("Image1");
        if (img != null)
        {
            img.ImageUrl = "data:image/png;base64," + ""; ???
        }
    }

由于

1 个答案:

答案 0 :(得分:0)

要将byte []转换为base64编码的字符串,您可以使用Convert.ToBase64String(byte[])方法。

根据您的代码,类似于以下内容应该有效:

protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Image img = (Image)e.Item.FindControl("Image1");
    if (img != null)
    {
        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            DataRowView row = e.Item.DataItem as DataRowView;

            byte[] data = (byte[])row["ImageData"]; // get your data from the row

            img.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(data); 
         }
    }
}