Can an ASP.NET MVC controller return an Image?

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

    Read the image, convert it to byte[], then return a File() with a content type.

    public ActionResult ImageResult(Image image, ImageFormat format, string contentType) {
      using (var stream = new MemoryStream())
        {
          image.Save(stream, format);
          return File(stream.ToArray(), contentType);
        }
      }
    }
    

    Here are the usings:

    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using Microsoft.AspNetCore.Mvc;
    

提交回复
热议问题