【问题标题】:Display Bitmap in Image Control在图像控件中显示位图
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 如果你从一个 .net Bitmap 对象开始,你需要这个中间步骤从 Bitmap 到一个字节数组:Model.imageBytes = (byte[])new ImageConverter()。 ConvertTo(qrCodeBitMap, typeof(byte[]));
    【解决方案2】:

    您需要有一个返回 FileStreamResult 的控制器操作,然后使用指向该操作的&lt;img /&gt; 标记。

    动作

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

    【讨论】:

    • 谢谢。不要忘记释放位图对象。
    猜你喜欢
    • 2017-02-18
    • 2012-07-05
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多