Base64 图像不会显示在 asp.net MVC 视图中
本文关键字:net MVC 视图 asp 图像 显示 Base64 | 更新日期: 2023-09-27 18:30:30
我想在剃刀视图中显示来自resx文件的图像:
My.cshtml:
<div>
@Model.ImageTag
</div
使用此帮助程序:
public static string CreateImageHtmlTag(this Bitmap bitmap)
{
ImageFormat format = null;
if (Equals(bitmap.RawFormat, ImageFormat.Png))
{
format = ImageFormat.Png;
}
else if (Equals(bitmap.RawFormat, ImageFormat.Jpeg))
{
format = ImageFormat.Jpeg;
}
else
{
throw new NotSupportedException("This image type is not supported!");
}
var stream = new MemoryStream();
bitmap.Save(stream, format);
stream.Seek(0, SeekOrigin.Begin);
var base64 = Convert.ToBase64String(stream.ToArray());
return $@"<img src='data:image/{format};base64,{base64}' />";
}
这显示在我的浏览器中:
"<img src='data:image/Png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABICAYAAABhlHJbAAAABHNCSVQICAgIfAhkiAAAAAFzUkdCAK7OHOkAAAAEZ0FNQQAAsY8L/GEFAAAACXBIWXMAABVlAAAVZQGF3cVdAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABnNJREFUeF7tnFls3EQYx11ucQshClWbtb1LC4RLIARIHAXxgsQDCOWhJGs7mypIoII4BAIhsYAEWY+TlEo8FAQSQjxAuR54AnFUFHH0CQlEEWcaQhpKmx5poVWb8H3eb92Jd7Nre8a7a2d/0l9txvN99vw1HnvtGSsdqskYzu2ayb4A7dNN9oNm2E8qPW8fT5s71EOznDwYdxQ0x0s12LtXD248kaoFpFg8TisMX6Gb9t264dwHSR5PtEz7Mc10BrE92b6RnKLMLaGWulDPO+w3ryLoje8FMlG37As1094IQX/7k6RJqsl+wdNz2WDxVDXProWyGX8dv+qamFu34WQwbz1UPOIPTLec3+HfndXltQU9+P0qE1Vr9GzY+K2/MugACAfUd8q9Mslir4M+BMO+oXb52xpYaOLq1cUTyLziKVCIJvGVtmYMdlf4gTMZ4NkGpjq+NoeTw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Eg73sX64QhbY0EKELy2f8fmQJGv0qrmWhXQnRtgYiqwqlMyD/Fn5fosJ3GLLMQ9raQERyT9wke+1a2xuISDHRYh/EsfQiEQYigiZ+jGtaKJVUEmMgEsVE+IXxJcZRCukkykAklIkW+xovRBQaC4kzEAlo4nfLB0bOoZDYSKSBCJpIM1y94+D0U7OOKbEGIrhet4aJY/hehKrETqINRHwmjvtfMsVN4g1EyjMg2KZWTFZPhYGtpGOgIB0DBekYKEjHQEE6BgrSMVAQEQP/rQTip
B4qXnRA+wcqPsANfYmKGwMB3kSeuNZzJIHyd7XKPuCiIipujGbaH1UCoRs/SMWLDmj/G56Blt1DxY2Byuu8QJNtlfGKMGngKwJo+yR5MJvNs/NoU2NWFErLIMgbB3WL3UObFg1wFhqV9uNUPSoODg6axxKwfXA1lrKiKAngnQe02fsEFH5bkDYFx51parBtlSSgvZESJQxae/Ij1+4tkd81w70PLlj+h0uG2gzG9uFpTtUST3dP8SQ8w2CoGoL28d8M2yX83RxcPqqazvdcUl6HQLtToFptm4COcjnZIAY+1ITT9xlIut+3kzQKlz+8GcsZtnKNc65mOGtxJgCNjw2/L5oA4adNJ/A1KVxtnxNdOaooivI/TJ7jyaaaFhoAAAAASUVORK5CYII=' />"
为什么不渲染图像,而只插入一个字符串?
将 cshtml 从:
<div>
@Model.ImageTag
</div>
自
<div>
@Html.Raw(@Model.ImageTag)
</div>
尝试返回MvcHtmlString
而不是string
。
public MvcHtmlString(
string value
)
看看这里更多解释:什么是 MvcHtmlString,我应该什么时候使用它?
您的 base64 代码是正确的,如果我解码它,它会作为图像打开。也许问题出在扩展名上(尝试使用 data:image/png 而不是 Png,所以小写)。
默认情况下返回一个字符串,当它收到字符串时不会转换您的 HTML 标记。Asp.net 提供标签Html.Raw(您的字符串)来帮助转换它。