关于MVC4中验证码的问题

a664565278 2015-06-18 09:51:28
public ActionResult CheckCode()
{
//生成验证码
ValidateCode validateCode = new ValidateCode();
string code = validateCode.CreateValidateCode(4);
Session["ValidateCode"] = code;
byte[] bytes = validateCode.CreateValidateGraphic(code);
return File(bytes, @"image/jpeg");
}
ValidateCode是一个生成验证码图片的方法,在最后时用了File()方法提交了图片,但我视图中除了这个验证码图片,其它空间都看不见了,我想知道,如何既能提交这个生成的图片,又能返回我的全局视图!
...全文
442 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
moonwrite 2015-06-19
  • 打赏
  • 举报
回复
<img src="/controller/CheckCode" /> 最后用绝对路径
  • 打赏
  • 举报
回复
图片是个单独的视图,然后<img src="url"/>
newtee 2015-06-19
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Drawing.Drawing2D;
using System.Drawing.Text;

namespace Blog.VerificationCode
{
internal class VerifyCode
{
public string MakeValidateCode()
{
char[] s = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
string num = "";
Random r = new Random();
for (int i = 0; i < 4; i++)
{
num += s[r.Next(0, s.Length)].ToString();
}
return num;
}

public byte[] CreateCheckCodeImage(string checkCode)
{
Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Brown, Color.DarkCyan, Color.Purple };
int len = colors.Length;
Random random = new Random(System.DateTime.Now.Millisecond);
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(checkCode.Length * 22d), 40);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
Color color = colors[random.Next(0, len)];
Brush brush = new SolidBrush(color);
g.SmoothingMode = SmoothingMode.AntiAlias;
int x1 = random.Next(0, image.Width/3);
int x2 = random.Next(2*image.Width/3,image.Width);
int y1 = random.Next(image.Height / 4, image.Height / 2);
int y2 = random.Next(3* image.Height / 4, 2*image.Height );
g.DrawLine(new Pen(color,2), x1, y1, x2, y2);
Twist tw = new Twist();
image = tw.TwistBitmap(image, false, 4, 2*Math.PI);
g.Dispose();

g = Graphics.FromImage(image);

using (StringFormat format = new StringFormat())
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.NoWrap;
Matrix matrix = new Matrix();
float offsetx = -30, offsety = 0;
for (int i = 0; i < checkCode.Length; i++)
{
int fsize = random.Next(14, 20);
Font f = new Font("AKANGEL", fsize, FontStyle.Bold, GraphicsUnit.Point, 0);
// Font f = CreateFont(System.Web.HttpContext.Current.Server.MapPath("AKANGEL.ttf"), fsize, FontStyle.Bold, GraphicsUnit.Point, 0);
SizeF size = g.MeasureString(checkCode[i].ToString(), f);
matrix.RotateAt(random.Next(-15, 15), new PointF(offsetx + size.Width / 2, offsety + size.Height / 2));
g.Transform = matrix;
g.DrawString(
checkCode[i].ToString(),
f,
brush,
new RectangleF(
offsetx,
offsety,
image.Width,
image.Height),
format);
offsetx += size.Width * 3 / 5;
offsety += -0;
g.RotateTransform(0);
matrix.Reset();
f.Dispose();
}
}

System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}

public static Font CreateFont(string fontFile, float fontSize, FontStyle fontStyle, GraphicsUnit graphicsUnit, byte gdiCharSet)
{
/*PrivateFontCollection 类允许应用程序安装现有字体的私有版本,而无需替换该字体的系统版本。例如,除系统使用的 Arial 字体外,GDI+ 还可以创建 Arial 字体的私有版本。PrivateFontCollection 还可以用于安装操作系统中不存在的字体。这种临时的字体安装不会影响系统安装的字体集合。若要查看已安装的字体集合,请使用 InstalledFontCollection 类。*/
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(fontFile);
return new Font(pfc.Families[0], fontSize, fontStyle, graphicsUnit, gdiCharSet);
}
}
}

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;

namespace Blog.VerificationCode
{
public class Twist
{
/// <summary>
/// 正弦曲线Wave扭曲图片
/// </summary>
/// <param name="srcBmp">图片路径</param>
/// <param name="bXDir">沿Y轴扭曲则选择为True</param>
/// <param name="dMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
/// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
/// <returns>扭曲后的位图</returns>
public Bitmap TwistBitmap(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
{
int w = srcBmp.Width;
int h = srcBmp.Height;
System.Drawing.Bitmap destBmp = new Bitmap(w, h);
using (System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp))
{
graph.Clear(Color.White);
}
double dBaseAxisLen = bXDir ? (double)h : (double)w;
BitmapData destData = destBmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, srcBmp.PixelFormat);
BitmapData srcData = srcBmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, srcBmp.PixelFormat);
//调式一定注意PixelFormat是多少,别处都没有解释的。如果是24下面指针和跨度就3倍,要是32就是4倍。
unsafe
{
byte* p = (byte*)srcData.Scan0;
byte* p2 = (byte*)destData.Scan0;
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
double dx = 0;
dx = bXDir ? (Math.PI * (double)j * 2) / dBaseAxisLen : (Math.PI * (double)i * 2) / dBaseAxisLen;
dx += dPhase;
double dy = Math.Sin(dx);
// 取得当前点
int nOldX = 0, nOldY = 0;
nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
nOldY = bXDir ? j : j + (int)(dy * dMultValue);

if ((nOldX >= 0 && nOldX < w) && (nOldY >= 0 && nOldY < h))
{
p2[(nOldY * destData.Stride) + (nOldX * 4)] = p[(j * srcData.Stride) + (i * 4)];
p2[(nOldY * destData.Stride) + (nOldX * 4) + 1] = p[(j * srcData.Stride) + (i * 4) + 1];
p2[(nOldY * destData.Stride) + (nOldX * 4) + 2] = p[(j * srcData.Stride) + (i * 4) + 2];
}
}
}
}
destBmp.UnlockBits(destData);
srcBmp.UnlockBits(srcData);
if (srcBmp != null)
srcBmp.Dispose();
return destBmp;
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Blog.VerificationCode;

namespace Blog.Controllers
{
public class VerificationCodeController : Controller
{
//验证码<img alt="验证码" src="/VerificationCode/Index" id="code_img" title="看不清请点击!" />
// GET: /VerificationCode/

public ActionResult Index()
{
VerifyCode vc = new VerifyCode();
string num = vc.MakeValidateCode();
System.Web.HttpContext.Current.Session["code"] = num.ToLower();//写入session
byte[] bytes = vc.CreateCheckCodeImage(num);
return File(bytes, @"image/jpeg");
}
}
}
a664565278 2015-06-19
  • 打赏
  • 举报
回复
引用 1 楼 caozhy 的回复:
这个单独做一个视图,FileResult 你的真正的视图放在另外。在你的视图上加上<img src="controller/CheckCode" />
不知道为什么,图片找不到,路径应该没错,我在后面验证码编辑框后面添加了<img src="HomeController/CheckCode" /> 打开View找不到,验证码以外的视图最后是用return View()返回视图吗?
风吹腚腚凉 2015-06-19
  • 打赏
  • 举报
回复
引用 2 楼 starfd 的回复:
图片是个单独的视图,然后<img src="url"/>
用一般处理程序也行。
threenewbee 2015-06-18
  • 打赏
  • 举报
回复
这个单独做一个视图,FileResult 你的真正的视图放在另外。在你的视图上加上<img src="controller/CheckCode" />

12,162

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 Web Services
社区管理员
  • Web Services社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧