【问题标题】:ASP.NET - Razor Get Image from modelASP.NET - Razor 从模型中获取图像
【发布时间】:2016-01-24 05:22:53
【问题描述】:

我有这个模型,imageFirst 和 imageLast 将是来自 Properties.Resources 的图像

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;

namespace Clinica_Imagine_Web.Models.ClinicCase {

    public class ClinicCase {

        public Bitmap imageFirst { get; set; }
        public Bitmap imageLast { get; set; }
        public string description { get; set; }
    }
}

在 htmlview 中我有这个例子

@using Clinica_Imagine_Web.Models.ClinicCase
@model ClinicCase

<h2>ClinicCase</h2>

<p>@Model.description</p>
<img src="@Model.imageFirst" />
<img src="@Model.imageLast" />

如何在 htmlview 中显示模型的图像?

【问题讨论】:

    标签: c# html asp.net razor


    【解决方案1】:

    在您的模型中使用 byte[] 数组代替位图。比你可以使用这个:

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

    这就是将位图转换为数组的方式:

    private static byte[] BitmapToBytes(Bitmap bitmap)
    {
        using (var stream = new MemoryStream())
        {
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            return stream.ToArray();
        }
    }
    

    【讨论】:

    • 好的,这个方法可行,但没有最简单的方法吗?
    • @Deinok 理想情况下,您在文件系统中有一个文件——这将是最简单的方法。但由于您使用位图进行操作,这几乎是您的唯一选择。您还可以通过在模型中传递 Base64 字符串而不是在 Razor 中甚至从 src 中转换整个字符串来简化一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2019-04-22
    • 1970-01-01
    • 2017-11-15
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多