.NET生成動(dòng)態(tài)驗(yàn)證碼的完整步驟
前言
驗(yàn)證碼是圖片上寫上幾個(gè)字,然后對這幾個(gè)字做特殊處理,如扭曲、旋轉(zhuǎn)、修改文字位置,然后加入一些線條,或加入一些特殊效果,使這些在人類能正常識(shí)別的同時(shí),機(jī)器卻很難識(shí)別出來,以達(dá)到防爬蟲、防機(jī)器人的效果。
驗(yàn)證碼通常用于網(wǎng)站中,是防爬蟲、防機(jī)器人侵入的好方法。以往.NET中創(chuàng)建驗(yàn)證碼,通常會(huì)使用System.Drawing
創(chuàng)建“正?!钡尿?yàn)證碼。
在前一往篇博客.NET中生成水印更好的方法中,提到了如何給圖片加水印。本文將基于上篇博客進(jìn)一步探索,使用Direct2D創(chuàng)建驗(yàn)證碼。
傳統(tǒng)System.Drawing
的做法
前置條件:引用System.Drawing
,或者安裝NuGet包:System.Drawing.Common
:
<PackageReference Include="System.Drawing.Common" Version="4.5.1" />
首先創(chuàng)建一個(gè)有幾個(gè)文字的圖片(基本操作):
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生成多次截圖而來,實(shí)際為靜態(tài)圖):
然后再加入一些線條:
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生成多次截圖而來,實(shí)際為靜態(tài)圖):
還能做什么?
很遺憾,還有很多可以做,即使是加入線條,機(jī)器依然能輕而易舉地識(shí)別出來。
不過Edi.Wang
在他的博客中也發(fā)布了一個(gè)生成驗(yàn)證碼的NuGet包:Edi.Captcha
,截止目前最新版是1.3.1:
<PackageReference Include="Edi.Captcha" Version="1.3.1" />
這個(gè)包基于System.Drawing
,加入了扭曲效果,加入了一些隨機(jī)的x坐標(biāo)偏移,極大地增加了AI識(shí)別的難度。
使用方式:
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生成多次截圖而來,實(shí)際為靜態(tài)圖):
Direct2D
在前一篇博客中,已經(jīng)有了Direct2D的相關(guān)簡介。這里將不再介紹。
首先從最簡單的圖片上寫文字開始:
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) * // 文字旋轉(zhuǎn)和扭曲效果,取消注釋以下兩行代碼 // 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生成多次截圖而來,實(shí)際為靜態(tài)圖):
可以注意到,Direct2D生成的文字沒有System.Drawing
那樣的鋸齒。
如果取消里面的兩行注釋,可以得到更加扭曲和旋轉(zhuǎn)的效果(Gif是由LINQPad生成多次截圖而來,實(shí)際為靜態(tài)圖):
然后加入線條:
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生成多次截圖而來,實(shí)際為靜態(tài)圖):
Direct2D的騷操作
Direct2D中內(nèi)置了許多特效,如陰影(Shadow)等,這里我們需要用到的是位移特效(Displacement)和水流特效(Turbulence),為了實(shí)現(xiàn)特效,需要加入一個(gè)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<D2D.DeviceContext>(); 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生成多次截圖而來,實(shí)際為靜態(tài)圖):
在此基礎(chǔ)上,(感謝Direct2D
/WIC)經(jīng)過較小的改動(dòng),即可生成一個(gè)動(dòng)態(tài)的Gif圖片。
只要略微修改以上代碼:
- 將
PngBitmapEncoder
改成GifBitmapEncoder
* - 然后將下面的
for
循環(huán)取消注釋 - 將
displacement.Scale = 100.0f;
改成displacement.Scale = Math.Abs(frameId) * 10.0f;
即可看到以下效果(直接生成,非截圖):
結(jié)語
最終的代碼生成效果,可以從這里下載,用LINQPad 6打開。
本文使用的是SharpDX,是C#到DirectX的轉(zhuǎn)換層。一個(gè)壞消息是,上圖中使用的SharpDX已經(jīng)停止維護(hù)了,但目前還沒找到可以用于替換的庫(可能由于它太好用了)。
以前我經(jīng)常將Direct2D用于游戲,但最近越來越多的時(shí)候Direct2D已經(jīng)用于解決實(shí)際問題。由于Direct2D的高顏值、高性能,實(shí)際上,Direct2D已經(jīng)無處不在,瀏覽器/Word/Excel等日常軟件都是深度集成Direct2D的應(yīng)用。相信Direct2D可以用于更多的場景中。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。
相關(guān)文章
解決iis7.5服務(wù)器上.net 獲取不到https頁面的信息
讓我糾結(jié)了一天多的問題,給大家看下,有相同情況的可以不用浪費(fèi)時(shí)間了,本人當(dāng)時(shí)找了好半天都沒找到什么有用的信息,項(xiàng)目在本地沒有問題,但部署在服務(wù)器后,獲取不到https頁面的信息,加入下面的代碼就可以了,因?yàn)閕is7.5的安全協(xié)議比較高的原因。2014-06-06.net?程序通過?crontab?無法啟動(dòng)手動(dòng)執(zhí)行腳本啟動(dòng)的方法
.net 網(wǎng)關(guān)程序需要設(shè)置定時(shí)重啟,按照日常操作先把正在運(yùn)行的 PID kill 掉后,再執(zhí)行啟動(dòng)服務(wù)。通過腳本無法啟動(dòng),試著把 .net 程序?qū)懗煞?wù)后,發(fā)現(xiàn)是可以正常重啟的,本文給大家介紹下.net 程序通過 crontab 無法啟動(dòng)手動(dòng)執(zhí)行腳本啟動(dòng),感興趣的朋友一起看看吧2021-12-12asp.net實(shí)現(xiàn)服務(wù)器文件下載到本地的方法
這篇文章主要介紹了asp.net實(shí)現(xiàn)服務(wù)器文件下載到本地的方法,需要的朋友可以參考下2017-02-02在DataTable中執(zhí)行Select("條件")后,返回DataTable的方法
在DataTable中執(zhí)行Select("條件")后,返回DataTable的方法...2007-09-09