[英]Image is saved to the database as binary data, now I need to extract the data and put it in an <img> tag
I please need help to get my image to display correctly in the tag that is created in a literal control. 我需要帮助以使我的图像正确显示在文字控件中创建的标记中。
foreach (DataRow dr in dt.Rows)
{
string productName = dr["PRO_Name"].ToString();
string productPrice = dr["PRO_Price"].ToString();
byte[] productImg = (byte[])dr["PRO_Img"];
string sProduct = @"<div class='four-shop columns isotope-item'>
<div class='shop-item'>
<figure>
//I need the image from the data base here:
<img src='" + productImg + "' alt='' />
<figcaption center code herelass='item-description'>
<h5>" + productName + "</h5>
<span>R" + productPrice + "</span>
<a href='#' class='button color'>Add to Cart</a</figcaption>
</figure>
</div>
</div>";
//Im using a literal control to create the DIV dynamically for each product in the database.
productPanel.Controls.Add(new LiteralControl(sProduct));
}
You may use a generic handler (.ashx)
that get productName and use Context.WriteBinary()
method in ashx
file. 您可以使用获取(.ashx)
的通用处理程序(.ashx)
,并在ashx
文件中使用Context.WriteBinary()
方法。 You should pass productName
to ashx
as a query string: 你应该通过productName
来ashx
作为查询字符串:
<img alt="Product image" src="~/somewhere/ImageHandler.ashx?productName=" + productName + "/>"
You should put the URL of your image in the img
's src
attribute and not a byte
array as you do now: 您应该将图像的URL放在img
的src
属性中,而不是像现在那样将byte
数组放置:
//Wrong:
byte[] productImg = (byte[])dr["PRO_Img"];
<img src='" + productImg + "' alt='' />
In order to achieve it, take a look at this answer about how to create an ASP.NET ASHX Handler and eventually retrieve the image using a URL: 为了实现它,请看以下有关如何创建ASP.NET ASHX处理程序并最终使用URL检索图像的答案:
Display image from database in ASP.net with C# 使用C#从ASP.net中的数据库显示图像
Depending on your browser needs and image size (I don't recommend it for large files), you may embed it as a base64 string. 根据您的浏览器需求和图像大小(不建议将其用于大文件),您可以将其作为base64字符串嵌入。 Look at: Embedding base64 images 查看: 嵌入base64图像
Try this 尝试这个
View: 视图:
<img src="@Url.Action("GetImg", "Home", new {id= Model.id})" alt="" width="150" height="200"/>
Controller: 控制器:
public FileContentResult GetImg(int id)
{
byte[] byteArray = new Model().GetImgByID(id);
if (byteArray != null)
{
return new FileContentResult(byteArray, "image/png");
}
else
{
//something failed, image not found!
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.