【发布时间】:2015-04-28 09:33:16
【问题描述】:
我想将图像直接显示到视图中,因此我正在调用一个操作方法并将图像写入输出流。
但我收到错误消息,提示“图像包含错误,无法显示”。我确定图像生成正确但不确定我的控制器代码有什么问题..有人遇到过这种情况吗?
提前谢谢..
这是我的控制器操作
[ChildActionOnly]
public ActionResult GetCaptcha()
{
try
{
this.Session["CaptchaImageText"] = GenerateRandomCode();
this.Response.Clear();
this.Response.ContentType = "image/jpeg";
Bitmap img = new Bitmap(Server.MapPath("../Images/captcha.jpg"));
Graphics graphicImage = Graphics.FromImage(img);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString(this.Session["CaptchaImageText"].ToString(),
new Font("Arial", 12, FontStyle.Bold),
SystemBrushes.WindowText, new Point(100, 250));
graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360);
//Save the new image to the response output stream.
img.Save(this.Response.OutputStream, ImageFormat.Jpeg);
// Create a CAPTCHA image using the text stored in the Session object.
graphicImage.Dispose();
img.Dispose();
}
catch (Exception ex)
{
ex = null;
}
var v = new FileStreamResult(Response.OutputStream,"image/jpeg");
return v;
}
这是我从视图中调用操作方法的方式
<tr><td> <iframe width="200px" height="80px" frameborder="1" scrolling="no"> <img src="@Url.Action("GetCaptcha")" alt="SimpleChart" /> </iframe> </td></tr>
【问题讨论】:
-
而不是从控制器操作返回
EmptyResult(),而是返回File(),而不是使用@Html.Action()内部视图使用@Url.Action() -
感谢您的快速回复。我尝试了您的建议,但没有运气..
codevar fileresult = new FileStreamResult(this.Response.OutputStream, "image/jpeg");返回文件结果; -
使用
<img src='@Url.Action("GetCaptcha")' />而不是在 iframe 中渲染图像 -
用更改更新了我的代码。现在没有错误,但图像没有加载
标签: asp.net-mvc image response outputstream