请求一个action,将图片的二进制字节字符串在视图页面以图片形式输出

有些时候需要将二进制图片字节在发送浏览器以图片形式显示:

下面是一些示例代码:

控制器:

     /// <summary>
/// 将图片的二进制字节字符串在视图页面以图片形式输出
/// </summary>
public class HomeController : Controller
{ public ActionResult Test()
{
return View();
} //方法一:
public FileResult TestFileResult_1()
{
byte[] mybyte;
using (WebClient client = new WebClient())
{
mybyte = client.DownloadData("http://img.baidu.com/video/img/video_logo_new.gif");
MemoryStream ms = new MemoryStream(mybyte);
//System.Drawing.Image img;
//img = System.Drawing.Image.FromStream(ms);
}
return File(mybyte, "image/gif");
} //方法二:
public FileResult TestFileResult()
{
byte[] mybyte;
using (WebClient client = new WebClient())
{
mybyte = client.DownloadData("http://img.baidu.com/video/img/video_logo_new.gif");
MemoryStream ms = new MemoryStream(mybyte);
//System.Drawing.Image img;
//img = System.Drawing.Image.FromStream(ms);
}
return new FileContentResult(mybyte, "image/gif");
} //方法三:
public ActionResult TestFileContentResult()
{
byte[] mybyte;
using (WebClient client = new WebClient())
{
mybyte = client.DownloadData("http://img.baidu.com/video/img/video_logo_new.gif");
MemoryStream ms = new MemoryStream(mybyte);
}
return new FileContentResult(mybyte, "image/gif");
} //方法四:
public ActionResult TestFile()
{
byte[] mybyte;
using (WebClient client = new WebClient())
{
mybyte = client.DownloadData("http://img.baidu.com/video/img/video_logo_new.gif");
//MemoryStream ms = new MemoryStream(mybyte);
//System.Drawing.Image img;
// img = System.Drawing.Image.FromStream(ms);
}
return File(mybyte, "image/gif");
} public ActionResult Index()
{
return View();
}
}

视图(view):

 @{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
} TestFile:<img src="@(Url.Action("TestFile", "Home"))"/>
<br/>
<br/>
TestFileContentResult:<img src="@(Url.Action("TestFileContentResult", "Home"))"/> <br/>
<br/>
TestFileResult:<img src="@(Url.Action("TestFileResult", "Home"))"/> <br/>
<br/>
TestFileResult:<img src="@(Url.Action("TestFileResult_1", "Home"))"/>

运行结果如下图所示:

请求一个action,将图片的二进制字节字符串在视图页面以图片形式输出

上一篇:php将图片以二进制保存到mysql数据库并显示


下一篇:IE浏览器直接在页面中显示7z文件而不是下载问题解决