在图像控件中显示位图

16

我正在开发ASP.NET MVC 5应用程序,需要在HTML标签<img />中从控制器中显示Bitmap图像。如何实现?

请注意: 这个问题不是“过于宽泛”。 它明确询问如何使用ASP.NET MVC在HTML图像标记中显示Bitmap C#对象。 请重新打开它。

2个回答

21
你可以简单地使用以下内容。
<img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model.imageBytes))" />

2
如果您从一个 .net Bitmap 对象开始,您需要进行以下中间步骤才能将 Bitmap 转换为字节数组:Model.imageBytes = (byte[])new ImageConverter().ConvertTo(qrCodeBitMap, typeof(byte[])); - Phred Menyhert

11

您需要编写一个控制器行为,返回一个FileStreamResult,并使用指向此行为的<img />标记。

行为(Action)

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="" />

1
谢谢。别忘了处理位图对象。 - Krisztián Balla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接