Display image from datatable in asp: encoded image

I have a datatable that is populated from a result set from a row select statement (through a stored procedure in SQL Server 2008) and contains a column Imagein which I store images.

I have a control asp:imageon an aspx page, and I want to set the image to the appropriate field of this datatable, but all I do is not able to. Please tell me how I can set the column asp:imageto the image of this datatable from the code located behind .

+3
source share
4 answers

Try the data url scheme :

<img src="<%# ReturnEncodedBase64UTF8(Eval("ColumnA")) %>" />

protected static string ReturnEncodedBase64UTF8(object rawImg)
{
    string img = "data:image/gif;base64,{0}"; //change image type if need be
    byte[] toEncodeAsBytes = (byte[])rawImg;        
    string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
    return String.Format(img, returnValue);
}
+2

<img src="data:image/png;base64,<BASE64 STRING>" />, asp:image ImageUrl "data:image/png;base64,xxx".

, , , IE9 firefox, .

, , ashx, . , : http://www.dotnetperls.com/ashx, ImageUrl .

+2

SQL Server ASP.Net

aspx file

<asp:image ID="Image1" runat="server" ImageUrl ="ImageCSharp.aspx?ImageID=1"/>

cs file

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["ImageID"] != null)
   {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value
        = Convert.ToInt32 (Request.QueryString["ImageID"]);
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename="
            + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}
+2

Convert.ToBase64String

        byte[] bytes = (byte[])dr["YourImageField"];
        string b64img = Convert.ToBase64String(bytes);
        Image1.ImageUrl = "data:image/jpeg;base64," + b64img;
0

All Articles