我想直接在视图中显示图像,所以我调用一个动作方法并在输出流中写入图像。
但我收到的错误是“图片无法显示,因为它包含错误”。我确信图像生成正常,但不确定我的控制器代码有什么问题..有没有人遇到过这种情况?
提前致谢..
这是我的控制器动作
[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;
}
以下是我从视图
调用action方法的方法 <tr><td> <iframe width="200px" height="80px" frameborder="1" scrolling="no"> <img src="@Url.Action("GetCaptcha")" alt="SimpleChart" /> </iframe> </td></tr>
答案 0 :(得分:1)
您需要返回文件而不是EmptyResult
。
return File(imageByteData, "image/png");
并在视图方面:
<tr><td> <iframe> <img src='@Url.Action("GetCaptcha")'/> </iframe> </td></tr>
<强>更新强>
不要写回复,而是在下面写。
[ChildActionOnly]
public ActionResult GetCaptcha()
{
try
{
byte[] imageByteData = null
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);
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Jpeg);
imageByteData = stream.ToArray();
// Create a CAPTCHA image using the text stored in the Session object.
graphicImage.Dispose();
img.Dispose();
return File(imageByteData, "image/png");
}
catch (Exception ex)
{
ex = null;
}
}
答案 1 :(得分:0)
我认为你使用的是FileStreamResult错误。
将img.Save(...)更改为内存流,并在FileStreamResult(...)中返回该内存流。