【问题标题】:Render image within razor view在剃刀视图中渲染图像
【发布时间】:2016-06-14 09:53:49
【问题描述】:

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

<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" />

所以我需要知道

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

谢谢,

【问题讨论】:

  • @downloader 请解释一下你的原因

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


【解决方案1】:

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

如果图像不是太大,现在最好的选择是提供一个 data-URI。

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

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

【讨论】:

  • 我得到了这个异常Failed to load resource: net::ERR_INVALID_URL
  • 啊好的,我只是在这一行中添加 base64 就可以了 string result = "data:image/jpg;base64," + Convert.ToBase64String(byteArray);
  • 确实如此。发现相同的:) 我不应该从头顶写。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多