在剃刀视图中渲染图像

时间:2016-06-14 09:53:49

标签: c# html asp.net asp.net-mvc razor

我有一个asp.net mvc 5应用程序,它与友好的api通信。所以,我创建了这部分视图:

<img src="@Html.Image(Model.Logo,25,25)" />

我添加了一个自定义html助手来显示徽标

   public static string Image(this HtmlHelper helper, byte[] byteArray, int newWidth, int newHeight)
    {
        FileContentResult arrayTof;
        if(byteArray==null)
        {
            string root = HttpContext.Current.Server.MapPath("~"); 

            var full = Path.Combine(root, "Content/events_medium.jpg");

            using (Image image = System.Drawing.Image.FromFile(full.ToString()))
            {
                using (MemoryStream m = new MemoryStream())
                {
                    image.Save(m, image.RawFormat);
                    byteArray = m.ToArray();
                }
            }
        }
        string result = "data:image/jpg;" + Convert.ToBase64String(byteArray);
        return result;
    }

        public static byte[] ResizeImage(byte[] myBytes, int newWidth, int newHeight)
        {
            byte[] imageArray = null;
            try
            {
                System.IO.MemoryStream myMemStream = new System.IO.MemoryStream(myBytes);
                System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(myMemStream);
                System.Drawing.Image newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
                System.IO.MemoryStream myResult = new System.IO.MemoryStream();
                newImage.Save(myResult, System.Drawing.Imaging.ImageFormat.Jpeg);
                return myResult.ToArray();
            }
            catch (Exception)
            {
            }
            return imageArray;

        }

我得到html结果:

 <img src="data:image/jpg;/9j/4AAQSkZJRgABAQEAZABkAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAE+AagDAREAAhEBAxEB/8QAHAAAAgIDAQEAAAAAAAAAAAAAAwQCBQEGBwAI/8QAURAAAgECBAQEAwUEBgYG" />

enter image description here

所以我需要知道

  1. 为什么不渲染图像?
  2. 我该如何解决这个问题?
  3. 谢谢,

1 个答案:

答案 0 :(得分:2)

因为src元素只接受一个字符串,所以你必须为它提供一个字符串。给FileContentResult只会导致它对提供的结果进行ToString

如果图像不是太大,你现在拥有的最佳选择是提供数据URI。

让你的方法返回这个字符串:

string result = "data:image/jpeg;base64," + Convert.ToBase64String(byteArray);