您好,登錄后才能下訂單哦!
如何在.NET中生成動(dòng)態(tài)驗(yàn)證碼?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
前置條件:引用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;
看完上述內(nèi)容,你們掌握如何在.NET中生成動(dòng)態(tài)驗(yàn)證碼的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。