C#工具:WPF生成图片验证码

时间:2023-03-08 20:57:56

1.使用ImageFormatConvertHelper

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging; namespace YongAn_WPF
{
public class ImageFormatConvertHelper
{
[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteObject(IntPtr hObject);
/// <summary> ///
/// 从bitmap转换成ImageSource ///
/// </summary> ///
/// <param name="icon"></param>
/// <returns></returns>
public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
{ //Bitmap bitmap = icon.ToBitmap();
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
if (!DeleteObject(hBitmap))
{ throw new System.ComponentModel.Win32Exception(); }
return wpfBitmap;
}
}
}

2.使用VerifyCodeHelper

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace YongAn_WPF
{
public class VerifyCodeHelper
{
public static Bitmap CreateVerifyCode(out string code)
{ //建立Bitmap对象,绘图
Bitmap bitmap = new Bitmap(, ); Graphics graph = Graphics.FromImage(bitmap);
graph.FillRectangle(new SolidBrush(Color.White), , , , );
Font font = new Font(FontFamily.GenericSerif, , FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random(); string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
//添加随机的五个字母
for (int x = ; x < ; x++)
{
string letter = letters.Substring(r.Next(, letters.Length - ), );
sb.Append(letter);
graph.DrawString(letter, font, new SolidBrush(Color.Black), x * , r.Next(, ));
}
code = sb.ToString();
//混淆背景
Pen linePen = new Pen(new SolidBrush(Color.Black), );
for (int x = ; x < ; x++) graph.DrawLine(linePen, new Point(r.Next(, ), r.Next(, )), new Point(r.Next(, ), r.Next(, )));
return bitmap;
}
}
}

3.调用方式 返回Code(验证码内容)

        public string GetImage()
{
string code = "";
Bitmap bitmap = VerifyCodeHelper.CreateVerifyCode(out code);
ImageSource imageSource = ImageFormatConvertHelper.ChangeBitmapToImageSource(bitmap);
img.Source = imageSource;
return code;
}