首页 > 解决方案 > How to return an image as an IActionResult from an Image/Bitmap object

问题描述

I am generating a Barcode image using the barcodelib library + the System.Drawing.Common package available in .Net Core.

I want to return the image to the users in their browser as a plain image (or as a download) but I seem to not find a good way to do so.

What I've tried:

var barcode = new Barcode().Encode(TYPE.CODE128, reference);
usuing (var outputStream = new MemoryStream()) 
{
    barcode.Save(outputStream, ImageFormat.Jpeg);
    outputStream.Seek(0, SeekOrigin.Begin);
    return File(outputStream, "image/jpeg");
}

This gives an exception, saying that the stream is closed.

It can be fixed by removing the using but isn't it bad? doesn't the streams stay in memory?

标签: c#imageasp.net-core

解决方案


删除. using_ outputStream流在被响应使用之前被关闭/处置。

使用FileResult完毕后将关闭流。

var barcode = new Barcode().Encode(TYPE.CODE128, reference);
var outputStream = new MemoryStream();
barcode.Save(outputStream, ImageFormat.Jpeg);
outputStream.Seek(0, SeekOrigin.Begin);
return File(outputStream, "image/jpeg");

推荐阅读