ASP.NET MVC how to return the next picture

method one:

First, we should start from the controller, which generally do not return View all of it? Back to picture how that? Of course, Controller class did not return Image of our last example is return JSON, in fact we can let it return a file stream, at the beginning I also thought about using ViewData, but this is only on the view page server-side code can be operated, if desired with JS, not so easy.

Controller File class has a method, of course, that there are N overloaded, and objects returned are not the same, here we have to find the type of return FileContentResult File method, because I tested, in the <img> element, src attribute can not FileStreamResult to read the contents of an object is blank, so can not return to get FileStreamResult.

Please refer to the following code is not complicated, let me draw a rectangle and then drawing some text on the rectangle, then return.

public ActionResult GetImg()  
{  
    Bitmap bmp = new Bitmap(100, 35);  
    Graphics g = Graphics.FromImage(bmp);  
    g.Clear(Color.White);  
    g.FillRectangle(Brushes.Red, 2, 2, 65, 31);  
    g.DrawString("学习MVC", new Font("黑体", 15f), Brushes.Yellow, new PointF(5f, 5f));  
    MemoryStream ms = new MemoryStream();  
    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);  
    g.Dispose();  
    bmp.Dispose();  
    return File(ms.ToArray(), "image/jpeg");  
}  

Note that this method is defined in your controller belonging to one Action.

In the front page, so we deal with.

  1. <div>  
  2.     <img src="/Home/GetImg" width="100" alt="" />  
  3. </div>  

In this way, we can when needed by the JS to operate, for example, returns a random picture, or code or something.

Second way

 public ActionResult GetQianming()
{
          //string strPath = //Server.MapPath("~/Resource/Image/5.jpg");
            string strPath = @"\\服务器IP\Signature\0a5ab89b-9963-430d-8dff-393f61e1fad3.png";
            Image img = Image.FromFile(strPath);
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return File(ms.ToArray(), "image/png");
}

Call the front desk

$("#ImageId").attr("src", "/Admin/Help/GetQianming"); //图片标签Id

 

Guess you like

Origin www.cnblogs.com/youmingkuang/p/11491197.html