0
点赞
收藏
分享

微信扫一扫

C#中两种生成验证码的方式


1、WPF使用 DrawingVisual 绘制验证码

  • 首先新建一个用户控件,封装生成的验证码图片

XAML样式

<Grid Loaded="CheckCode_Loaded">
<Image Source="{Binding ImageSource,RelativeSource={RelativeSource AncestorType={x:Type local:CheckCode}}}"
MouseLeftButtonDown="Image_MouseLeftButtonDown"/>
</Grid>

后台代码
 ​​​[Obsolete]​​​ 之所以会有他,是因为我用的是​​.net Core3.1​​的版本,有版本问题

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Verification_Code
{
/// <summary>
/// CheckCode.xaml 的交互逻辑
/// </summary>
public partial class CheckCode : UserControl
{
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(CheckCode), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

/// <summary>
/// 随机生成的验证码
/// </summary>
public ImageSource ImageSource
{
get
{
return (ImageSource)GetValue(ImageSourceProperty);
}
set
{
SetValue(ImageSourceProperty, value);
}
}

public CheckCode()
{
InitializeComponent();
}

[Obsolete]
private void CheckCode_Loaded(object sender, RoutedEventArgs e)
=> ImageSource = CreateCheckCodeImage(CreateCode(4), (int)Width, (int)Height);


private static string CreateCode(int strLength)
{
var strCode = "abcdefhkmnprstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; ;
var _charArray = strCode.ToCharArray();
var randomCode = "";
int temp = -1;

Random rand = new Random(Guid.NewGuid().GetHashCode());
for (int i = 0; i < strLength; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(strCode.Length - 1);
if (!string.IsNullOrWhiteSpace(randomCode))
{
while (randomCode.ToLower().Contains(_charArray[t].ToString().ToLower()))
{
t = rand.Next(strCode.Length - 1);
}
}
if (temp == t)
{
return CreateCode(strLength);
}
temp = t;

randomCode += _charArray[t];
}
return randomCode;
}

[Obsolete]
private ImageSource CreateCheckCodeImage(string checkCode, int width, int height)
{
if (string.IsNullOrWhiteSpace(checkCode))
return null;
if (width <= 0 || height <= 0)
return null;
DrawingVisual drawingVisual = new DrawingVisual();

Random random = new Random(Guid.NewGuid().GetHashCode());

using (DrawingContext dc = drawingVisual.RenderOpen())
{
dc.DrawRectangle(Brushes.White, new Pen(Brushes.Silver, 1D), new Rect(new Size(70, 23)));
FormattedText formattedText = new FormattedText(checkCode,
System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface(new FontFamily("Arial"), FontStyles.Oblique, FontWeights.Bold, FontStretches.Normal),
20.001D, new LinearGradientBrush(Colors.Green, Colors.DarkRed, 1.2D))
{
MaxLineCount = 1,
TextAlignment = TextAlignment.Justify,
Trimming = TextTrimming.CharacterEllipsis
};

dc.DrawText(formattedText, new Point(3D, 0.1D));

for (int i = 0; i < 10; i++)
{
int x1 = random.Next(width - 1);
int y1 = random.Next(height - 1);
int x2 = random.Next(width - 1);
int y2 = random.Next(height - 1);

dc.DrawGeometry(Brushes.Silver, new Pen(Brushes.Silver, 0.5D), new LineGeometry(new Point(x1, y1), new Point(x2, y2)));
}

for (int i = 0; i < 100; i++)
{
int x = random.Next(width - 1);
int y = random.Next(height - 1);
SolidColorBrush c = new SolidColorBrush(Color.FromRgb((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255)));
dc.DrawGeometry(c, new Pen(c, 1D), new LineGeometry(new Point(x - 0.5, y - 0.5), new Point(x + 0.5, y + 0.5)));
}
dc.Close();
}
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(70, 23, 96, 96, PixelFormats.Pbgra32);
renderBitmap.Render(drawingVisual);
return BitmapFrame.Create(renderBitmap);
}

[Obsolete]
private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
=> ImageSource = CreateCheckCodeImage(CreateCode(4), (int)Width, (int)Height);
}
}

在主窗体中调用

<Grid>
<Viewbox>
<Border Height="150" Width="500">
<local:CheckCode Width="150" Height="50"/>
</Border>
</Viewbox>
</Grid>

C#中两种生成验证码的方式_验证码

2、建立 Bitmap 对象,作为画布生成验证码

这种方式 更多的用于 web 页面,也是之前项目中使用的

using System;
using System.Drawing;
using System.Text;

public static Bitmap CreateVerifyCode(out string code)
{
//建立Bitmap对象,绘图
Bitmap bitmap = new Bitmap(200, 60);
Graphics graph = Graphics.FromImage(bitmap);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random();
string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";

StringBuilder sb = new StringBuilder();

//添加随机的五个字母
for (int x = 0; x < 5; x++)
{
string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
sb.Append(letter);
graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
}
code = sb.ToString();

//混淆背景
Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
for (int x = 0; x < 6; x++)
graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
return bitmap;
}

C#中两种生成验证码的方式_System_02

并不是说,不同的项目只能使用其中的一种,看个人喜好,均可
个人比较喜欢第二种,简单易于理解


举报

相关推荐

0 条评论