Can an ASP.NET MVC controller return an Image?

前端 未结 19 1880
旧时难觅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:40

    Below code utilizes System.Drawing.Bitmap to load the image.

    using System.Drawing;
    using System.Drawing.Imaging;
    
    public IActionResult Get()
    {
        string filename = "Image/test.jpg";
        var bitmap = new Bitmap(filename);
    
        var ms = new System.IO.MemoryStream();
        bitmap.Save(ms, ImageFormat.Jpeg);
        ms.Position = 0;
        return new FileStreamResult(ms, "image/jpeg");
    }
    

提交回复
热议问题