ASP.NET误人子弟教程:在MVC下如何返回图片
时间: 2023-12-10 11:03:24 浏览: 41
在MVC下返回图片,可以通过以下步骤实现:
1. 在Controller中创建一个Action用于返回图片,例如:
```
public ActionResult GetImage()
{
string imagePath = // 图片路径
byte[] imageBytes = System.IO.File.ReadAllBytes(imagePath);
return File(imageBytes, "image/jpeg");
}
```
2. 在View中通过img标签引用该Action,例如:
```
<img src="@Url.Action("GetImage")" />
```
3. 如果需要在Controller中动态生成图片并返回,可以使用以下代码:
```
public ActionResult GetDynamicImage()
{
// 生成图片
Bitmap bitmap = new Bitmap(200, 200);
Graphics g = Graphics.FromImage(bitmap);
g.Clear(Color.White);
g.DrawString("Hello World!", new Font("Arial", 16), Brushes.Black, new PointF(10, 10));
// 将图片转换为byte数组
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
// 返回图片
return File(imageBytes, "image/jpeg");
}
```
需要注意的是,动态生成图片的过程可能比较耗时,建议使用缓存技术来提高性能。