c# - 将图像从 Controller 传递到 View

标签 c# asp.net-mvc

我正在尝试将图像从 Controller 传递到 View :

Controller :

model.image = AspectRatio(String.Format("~" + i.ImageUrl));
return View(model);

型号:

public Bitmap image { get; set; }

查看:

@model OnlineStore.ViewModels.ItemVM
<div>
    @Model.image
<div>

代码没有抛出错误,但浏览器不显示图像,而是显示以下文本行:

System.Drawing.Bitmap

有人可以指导一下吗?

最佳答案

Bitmap 实例传递给没有显示任何图像的 razor View ,因为超文本传输​​协议(protocol),如果您想显示图像,您可以使用 img 标签。

型号:

您可以尝试使用byte数组属性imageBuffer来携带您的图像数据。

public byte[] imageBuffer { get; set; }

Controller :

使用ImageConverterBitmap对象图像数据转为byte[]

ImageConverter converter = new ImageConverter();

Bitmap imageObj = AspectRatio(String.Format("~" + i.ImageUrl));

model.imageBuffer = (byte[])converter.ConvertTo(imageObj, typeof(byte[]));

return View(model);

查看:

Convert.ToBase64String 函数让 byte[] 转换为 Base64 字符串。 img标签支持通过base64显示图像,只需设置src属性并在其中声明data:image/png;base64即可。

因为img标签支持base64数据

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

引用链接

what does this mean ? image/png;base64?

关于c# - 将图像从 Controller 传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362212/

相关文章:

c# - 使用依赖注入(inject)的带有构造函数的自定义 NLog LayoutRenderer

c# - 尝试运行 Fluent NHibernate 教程示例时出现运行时错误

c# - Frame.navigate 和 NagivationService 不工作

c# - 尝试使用自定义类进行用户设置时出现 NotImplementedException

jquery - MVC4 中不引人注目的客户端验证不起作用

c# - 国际奥委会 : CaSTLe Windsor and WebAPI

asp.net-mvc - WebApi 帮助页面说明

asp.net - 我可以使用 asp :Button like an Html. ActionLink 吗?

c# - HttpCacheability.NoCache 和 Response.CacheControl = "no-cache"之间有什么不同?

javascript - 如何更改此 JS 脚本以发出 "GET"而不是 "POST"调用