我有一个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" />
所以我需要知道
谢谢,
答案 0 :(得分:2)
因为src
元素只接受一个字符串,所以你必须为它提供一个字符串。给FileContentResult
只会导致它对提供的结果进行ToString
。
如果图像不是太大,你现在拥有的最佳选择是提供数据URI。
让你的方法返回这个字符串:
string result = "data:image/jpeg;base64," + Convert.ToBase64String(byteArray);