在图像控件中显示位图

12 .net html c# asp.net-mvc asp.net-mvc-5

我正在开发ASP.NET MVC 5应用程序.我需要在HTML标签中显示来自控制器的位图图像<img />.我该怎么做?

请阅读:这个问题不是"太宽泛".它特别询问如何Bitmap使用ASP.NET MVC在HTML图像标记中显示C#对象.请重新打开它.

Shi*_*Tal 12

您可以简单地使用以下内容

<img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model.imageBytes))" />
Run Code Online (Sandbox Code Playgroud)

  • 如果您从 .net Bitmap 对象开始,则需要此中间步骤从 Bitmap 转换为字节数组: Model.imageBytes = (byte[])new ImageConverter().ConvertTo(qrCodeBitMap, typeof(byte[ ])); (2认同)

And*_*rei 10

您需要有一个控制器操作,它返回一个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

视图

<img src='@Url.Action("image")' alt="" />
Run Code Online (Sandbox Code Playgroud)