在asp.net mvc视图中不显示base64图像

时间:2016-01-15 14:35:30

标签: c# asp.net-mvc base64 png

我想在剃刀视图中显示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=' />"

为什么不渲染图像而只插入一个字符串?

4 个答案:

答案 0 :(得分:0)

你的base64代码是正确的,如果我解码它会打开它作为图像。也许问题在于扩展(尝试使用数据:image / png而不是Png,所以小写)。

答案 1 :(得分:0)

尝试返回MvcHtmlString而不是string

public MvcHtmlString(
     string value
)

在这里查看更多解释: What is an MvcHtmlString and when should I use it?

答案 2 :(得分:0)

更改您的cshtml:

<div>
        @Model.ImageTag
</div>

<div>
        @Html.Raw(@Model.ImageTag)
</div>

答案 3 :(得分:0)

默认情况下返回一个字符串在收到字符串时不转换你的html标签。 Asp.net提供标签 Html.Raw(您的字符串)以帮助转换它。