Lamloumi Afif Lamloumi Afif - 1 year ago 160
HTML Question

Render image within razor view

I have an mvc 5 application which communicates with a friendly api. So, I create this part of view :

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

and I added a custom html helper to display the logo

public static string Image(this HtmlHelper helper, byte[] byteArray, int newWidth, int newHeight)
FileContentResult arrayTof;
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;
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;


I get as html result :


enter image description here

So I need to know

  1. Why the image is not rendered?

  2. How can I fix this?


Answer Source

Because the src element only accepts a string, you have to supply a string to it. Giving a FileContentResult just causes it to do a ToString on the supplied result.

The best option you have now, if the image is not too big, is to give a data-URI.

Let your method return this string:

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