Lamloumi Afif Lamloumi Afif - 5 months ago 42
HTML Question

Render image within razor view

I have an asp.net 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;
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;

}


I get as html result :

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


enter image description here

So I need to know


  1. Why the image is not rendered?

  2. How can I fix this?



Thanks,

Answer

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);
Comments