我想从某个路径获取图像,将其转换为字节并将其返回到 View 以显示它。
我有一个方法,它采用图像名称/扩展名并从目录中获取图像并将其转换为字节数组,如下所示
首先,我尝试将其作为 File
返回,如下所示
public IActionResult getImage(string image)
{
var fullPath = Path.Combine("C:\\images\\", image);
FileStream fs = new FileStream(fullPath, FileMode.Open);
byte[] fileBytes = new byte[fs.Length];
fs.Close();
return File(fileBytes , "image/png");
}
这对我不起作用,因为它在 Webroot
中查找图像,例如“Image/Image-name.png”
然后我尝试通过 HttpResponseMessage
编写它,如下所示
public HttpResponseMessage getImage(string image)
{
var fullPath = Path.Combine("C:\\images\\", image);
FileStream fs = new FileStream(fullPath, FileMode.Open);
byte[] fileBytes = new byte[fs.Length];
fs.Close();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(fileBytes);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
这是我的 Razor View
<img src="@Url.Action("getImage", "Image", new{ image=Model.Image})" />
最佳解决方案是将其作为 HttpResponse
返回并在 razor View 中使用它
最佳答案
您可以删除代码并高效地完成任务😁:
public IActionResult getImage(string image)
{
var fullPath = Path.Combine("C:\\images\\", image);
return PhysicalFile(fullPath, "image/png");
}
关于c# - 返回字节数组作为具有 Image/png 内容类型的 Http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76762101/