【发布时间】:2014-11-06 08:59:34
【问题描述】:
我正在开发 ASP.NET MVC 5 应用程序。我需要在 HTML 标签<img /> 中显示来自控制器的位图图像。我该怎么做?
请阅读:这个问题不是“太宽泛”。它专门询问如何使用 ASP.NET MVC 在 HTML 图像标签中显示 Bitmap C# 对象。请重新打开它。
【问题讨论】:
标签: c# html .net asp.net-mvc asp.net-mvc-5
我正在开发 ASP.NET MVC 5 应用程序。我需要在 HTML 标签<img /> 中显示来自控制器的位图图像。我该怎么做?
请阅读:这个问题不是“太宽泛”。它专门询问如何使用 ASP.NET MVC 在 HTML 图像标签中显示 Bitmap C# 对象。请重新打开它。
【问题讨论】:
标签: c# html .net asp.net-mvc asp.net-mvc-5
您可以简单地使用以下内容
<img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model.imageBytes))" />
【讨论】:
您需要有一个返回 FileStreamResult 的控制器操作,然后使用指向该操作的<img /> 标记。
public ActionResult Image()
{
var bitmap = GetBitmap(); // The method that returns Bitmap
var bitmapBytes = BitmapToBytes(bitmap); //Convert bitmap into a byte array
return File(bitmapBytes, "image/jpeg"); //Return as file result
}
// This method is for converting bitmap into a byte array
private static byte[] BitmapToBytes(Bitmap img)
{
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
return stream.ToArray();
}
}
<img src='@Url.Action("image")' alt="" />
【讨论】: