c# - 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?
解决方案
删除. 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");
推荐阅读
- python - 在 Django 中使用表单时如何将对象添加到不同的模型?
- angular - Ag-grid服务器端infiniteScroll在滚动页面时不断获取数据
- facebook - 如何检测我的应用程序中更改的 Facebook 密码(我在我的应用程序中使用 facebook 登录)
- google-api - 调用 https://accounts.google.com/o/oauth2/token 时获取“格式错误的身份验证代码”
- c# - Azure 函数在 blob 触发期间找不到 blob
- java - 在密封类上的 when 表达式中使用“is”会导致运行时反射吗?
- html - 无法使用 CSS 修复 RShiny 应用程序中页脚的位置
- python - 神经网络的 NP 数组输入导致形状错误
- azure-devops - 有没有办法识别在 Azure Devops CI 构建中签入的 TFS 分支?
- macos - IntelliJ IDEA 无法移动多个 Kotlin 类