ASP.NET MVC でコントローラから画像を返す

こんばんは。きわさです。

PHPでもやりましたが、今回はASP.NETで動的に画像を生成して返す方法です。
MVCのコントローラでビューを返す時はこのように書きますが、今回は画像を返してみます。

1
2
3
4
public ActionResult Index()
{
    return View();
}

画像を返す場合は、次のようにストリームに読み込んだ後に FileContentResult として返せば良いです。
TestImage() は仮です。動的に Bitmap を生成するメソッドとします。
また、動的に生成する場合は、画像がキャッシュされると都合が悪いのでキャッシュさせないようにします。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public ActionResult Image()
{
    ActionResult result;
     
    // 画像を取得
    Bitmap img = TestImage();
 
    using (var stream = new MemoryStream())
    {
        // 画像をストリームに保存
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
 
        // ストリームから読み込みレスポンス(FileContentResult)を生成
        result = File(stream.ToArray(), "image/png");
    }
 
    // 画像をキャッシュさせない
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetNoStore();
 
    return result;
}

スポンサーリンク