问题
I have a datatable which is filled from the resultset of a 1 row select statement (via a stored procedure in SQL Server 2008) and it contains a Image typed column which I store images in.
I have an asp:image control on an aspx page and i want to set the image to the corresponding field of that datatable but anything I do I can not.
Please tell me how can I set the asp:image to image column of that datatable from the code behind.
回答1:
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:
You could put <img src="data:image/png;base64,<BASE64 STRING>" />, so you would set the asp:image's ImageUrl property to "data:image/png;base64,xxx".
However, I suspect the browser support on this is spotty, works fine in IE9 and firefox, but I'm unsure of older browsers support for this.
An alternative I would recommend though, is to create a generic handler ashx, that reads the database and returns an image. You can check out this website on how to do it: http://www.dotnetperls.com/ashx, you would then set the ImageUrl property to this handlers address.
回答3:
Display Images from SQL Server Database using 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();
}
}
}
回答4:
Simply by using Convert.ToBase64String
byte[] bytes = (byte[])dr["YourImageField"];
string b64img = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:image/jpeg;base64," + b64img;
来源:https://stackoverflow.com/questions/10143323/display-image-from-a-datatable-in-aspimage-in-code-behind