Can an ASP.NET MVC controller return an Image?

前端 未结 19 1640
旧时难觅i
旧时难觅i 2020-11-22 02:10

Can I create a Controller that simply returns an image asset?

I would like to route this logic through a controller, whenever a URL such as the following is requeste

19条回答
  •  终归单人心
    2020-11-22 02:44

    This might be helpful if you'd like to modify the image before returning it:

    public ActionResult GetModifiedImage()
    {
        Image image = Image.FromFile(Path.Combine(Server.MapPath("/Content/images"), "image.png"));
    
        using (Graphics g = Graphics.FromImage(image))
        {
            // do something with the Graphics (eg. write "Hello World!")
            string text = "Hello World!";
    
            // Create font and brush.
            Font drawFont = new Font("Arial", 10);
            SolidBrush drawBrush = new SolidBrush(Color.Black);
    
            // Create point for upper-left corner of drawing.
            PointF stringPoint = new PointF(0, 0);
    
            g.DrawString(text, drawFont, drawBrush, stringPoint);
        }
    
        MemoryStream ms = new MemoryStream();
    
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    
        return File(ms.ToArray(), "image/png");
    }
    

提交回复
热议问题