如何在.NET中生成动态验证码-创新互联
如何在.NET中生成动态验证码?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
创新互联建站是一家集网站建设,太和企业网站建设,太和品牌网站建设,网站定制,太和网站建设报价,网络营销,网络优化,太和网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。前置条件:引用System.Drawing
,或者安装NuGet包:System.Drawing.Common
:
首先创建一个有几个文字的图片(基本操作):
byte[] GetImage(int width, int height, string text) { using (var bitmap = new Bitmap(width, height)) using (var g = Graphics.FromImage(bitmap)) { var r = new Random(); g.Clear(ColorFromHsl(r.NextDouble(), 1.0f, 0.8f, 0xff)); var brush = new SolidBrush(Color.Black); var fontSize = width / text.Length; var font = new Font(FontFamily.GenericSerif, fontSize, FontStyle.Bold, GraphicsUnit.Pixel); for (var i = 0; i < text.Length; i++) { brush.Color = ColorFromHsl(r.NextDouble(), 1.0f, 0.3f, 0xff); float x = i * fontSize; float y = r.Next(0, height - fontSize); g.DrawString(text[i].ToString(), font, brush, x, y); } // 在这里面加入一些其它效果 var ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.Png); return ms.ToArray(); } }
效果(Gif是由LINQPad生成多次截图而来,实际为静态图):
然后再加入一些线条:
using (var pen = new Pen(brush, 3)) { for (var i = 0; i < 4; ++i) { pen.Color = ColorFromHsl(r.NextDouble(), 1.0f, 0.4f, 0xff); var p1 = new Point(r.Next(width), r.Next(height)); var p2 = new Point(r.Next(width), r.Next(height)); g.DrawLine(pen, p1, p2); } }
效果(Gif是由LINQPad生成多次截图而来,实际为静态图):
还能做什么?
很遗憾,还有很多可以做,即使是加入线条,机器依然能轻而易举地识别出来。
不过Edi.Wang
在他的博客中也发布了一个生成验证码的NuGet包:Edi.Captcha
,截止目前新版是1.3.1:
这个包基于System.Drawing
,加入了扭曲效果,加入了一些随机的x坐标偏移,极大地增加了AI识别的难度。
使用方式:
CaptchaResult result = CaptchaImageGenerator.GetImage(200, 100, "HELLO");
其中CaptchaResult的定义如下:
public class CaptchaResult { public string CaptchaCode { get; set; } public byte[] CaptchaByteData { get; set; } public string CaptchBase64Data => Convert.ToBase64String(CaptchaByteData); public DateTime Timestamp { get; set; } }
生成的效果如下(Gif是由LINQPad生成多次截图而来,实际为静态图):
Direct2D
在前一篇博客中,已经有了Direct2D的相关简介。这里将不再介绍。
首先从最简单的图片上写文字开始:
byte[] SaveD2DBitmap(int width, int height, string text) { using var wic = new WIC.ImagingFactory2(); using var d2d = new D2D.Factory(); using var wicBitmap = new WIC.Bitmap(wic, width, height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand); using var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()); using var dwriteFactory = new SharpDX.DirectWrite.Factory(); using var brush = new SolidColorBrush(target, Color.Yellow); var r = new Random(); target.BeginDraw(); target.Clear(ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.3f)); var textFormat = new DWrite.TextFormat(dwriteFactory, "Times New Roman", DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, width / text.Length); for (int charIndex = 0; charIndex < text.Length; ++charIndex) { using var layout = new DWrite.TextLayout(dwriteFactory, text[charIndex].ToString(), textFormat, float.MaxValue, float.MaxValue); var layoutSize = new Vector2(layout.Metrics.Width, layout.Metrics.Height); using var b2 = new LinearGradientBrush(target, new D2D.LinearGradientBrushProperties { StartPoint = Vector2.Zero, EndPoint = layoutSize, }, new GradientStopCollection(target, new[] { new GradientStop{ Position = 0.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f) }, new GradientStop{ Position = 1.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f) }, })); var position = new Vector2(charIndex * width / text.Length, r.NextFloat(0, height - layout.Metrics.Height)); target.Transform = Matrix3x2.Translation(-layoutSize / 2) * // 文字旋转和扭曲效果,取消注释以下两行代码 // Matrix3x2.Skew(r.NextFloat(0, 0.5f), r.NextFloat(0, 0.5f)) * // Matrix3x2.Rotation(r.NextFloat(0, MathF.PI * 2)) * Matrix3x2.Translation(position + layoutSize / 2); target.DrawTextLayout(Vector2.Zero, layout, b2); } // 其它效果在这里插入 target.EndDraw(); using (var encoder = new WIC.BitmapEncoder(wic, WIC.ContainerFormatGuids.Png)) using (var ms = new MemoryStream()) { encoder.Initialize(ms); using (var frame = new WIC.BitmapFrameEncode(encoder)) { frame.Initialize(); frame.SetSize(wicBitmap.Size.Width, wicBitmap.Size.Height); var pixelFormat = wicBitmap.PixelFormat; frame.SetPixelFormat(ref pixelFormat); frame.WriteSource(wicBitmap); frame.Commit(); } encoder.Commit(); return ms.ToArray(); } }
使用方式:
byte[] captchaBytes = SaveD2DBitmap(200, 100, "Hello");
效果(Gif是由LINQPad生成多次截图而来,实际为静态图):
可以注意到,Direct2D生成的文字没有System.Drawing
那样的锯齿。
如果取消里面的两行注释,可以得到更加扭曲和旋转的效果(Gif是由LINQPad生成多次截图而来,实际为静态图):
然后加入线条:
for (var i = 0; i < 4; ++i) { target.Transform = Matrix3x2.Identity; brush.Color = ColorFromHsl(r.NextFloat(0,1), 1.0f, 0.3f); target.DrawLine( r.NextVector2(Vector2.Zero, new Vector2(width, height)), r.NextVector2(Vector2.Zero, new Vector2(width, height)), brush, 3.0f); }
效果(Gif是由LINQPad生成多次截图而来,实际为静态图):
Direct2D的骚操作
Direct2D中内置了许多特效,如阴影(Shadow)等,这里我们需要用到的是位移特效(Displacement)和水流特效(Turbulence),为了实现特效,需要加入一个Bitmap层,整体代码如下:
byte[] SaveD2DBitmap(int width, int height, string text) { using var wic = new WIC.ImagingFactory2(); using var d2d = new D2D.Factory(); using var wicBitmap = new WIC.Bitmap(wic, width, height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand); using var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()); using var dwriteFactory = new SharpDX.DirectWrite.Factory(); using var brush = new D2D.SolidColorBrush(target, Color.Yellow); using var encoder = new WIC.PngBitmapEncoder(wic); // PngBitmapEncoder using var ms = new MemoryStream(); using var dc = target.QueryInterface(); using var bmpLayer = new D2D.Bitmap1(dc, target.PixelSize, new D2D.BitmapProperties1(new D2D.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), d2d.DesktopDpi.Width, d2d.DesktopDpi.Height, D2D.BitmapOptions.Target)); var r = new Random(); encoder.Initialize(ms); D2D.Image oldTarget = dc.Target; { dc.Target = bmpLayer; dc.BeginDraw(); var textFormat = new DWrite.TextFormat(dwriteFactory, "Times New Roman", DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, width / text.Length); for (int charIndex = 0; charIndex < text.Length; ++charIndex) { using var layout = new DWrite.TextLayout(dwriteFactory, text[charIndex].ToString(), textFormat, float.MaxValue, float.MaxValue); var layoutSize = new Vector2(layout.Metrics.Width, layout.Metrics.Height); using var b2 = new D2D.LinearGradientBrush(dc, new D2D.LinearGradientBrushProperties { StartPoint = Vector2.Zero, EndPoint = layoutSize, }, new D2D.GradientStopCollection(dc, new[] { new D2D.GradientStop{ Position = 0.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f) }, new D2D.GradientStop{ Position = 1.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f) }, })); var position = new Vector2(charIndex * width / text.Length, r.NextFloat(0, height - layout.Metrics.Height)); dc.Transform = Matrix3x2.Translation(-layoutSize / 2) * Matrix3x2.Skew(r.NextFloat(0, 0.5f), r.NextFloat(0, 0.5f)) * //Matrix3x2.Rotation(r.NextFloat(0, MathF.PI * 2)) * Matrix3x2.Translation(position + layoutSize / 2); dc.DrawTextLayout(Vector2.Zero, layout, b2); } for (var i = 0; i < 4; ++i) { target.Transform = Matrix3x2.Identity; brush.Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.3f); target.DrawLine( r.NextVector2(Vector2.Zero, new Vector2(width, height)), r.NextVector2(Vector2.Zero, new Vector2(width, height)), brush, 3.0f); } target.EndDraw(); } Color background = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.3f); // for (var frameId = -10; frameId < 10; ++frameId) { dc.Target = null; using var displacement = new D2D.Effects.DisplacementMap(dc); displacement.SetInput(0, bmpLayer, true); displacement.Scale = 100.0f; // Math.Abs(frameId) * 10.0f; var turbulence = new D2D.Effects.Turbulence(dc); displacement.SetInputEffect(1, turbulence); dc.Target = oldTarget; dc.BeginDraw(); dc.Clear(background); dc.DrawImage(displacement); dc.EndDraw(); using (var frame = new WIC.BitmapFrameEncode(encoder)) { frame.Initialize(); frame.SetSize(wicBitmap.Size.Width, wicBitmap.Size.Height); var pixelFormat = wicBitmap.PixelFormat; frame.SetPixelFormat(ref pixelFormat); frame.WriteSource(wicBitmap); frame.Commit(); } } encoder.Commit(); return ms.ToArray(); }
注意此代码使用了using var
语句,是C# 8.0的using declaration
功能,可以用using (var )
语句代替。
效果如下(Gif是由LINQPad生成多次截图而来,实际为静态图):
在此基础上,(感谢Direct2D
/WIC)经过较小的改动,即可生成一个动态的Gif图片。
只要略微修改以上代码:
将
PngBitmapEncoder
改成GifBitmapEncoder
*然后将下面的
for
循环取消注释将
displacement.Scale = 100.0f;
改成displacement.Scale = Math.Abs(frameId) * 10.0f;
看完上述内容,你们掌握如何在.NET中生成动态验证码的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
网站名称:如何在.NET中生成动态验证码-创新互联
URL网址:http://ybzwz.com/article/dcpeoe.html