C#工具:WPF生成图片验证码
程序员文章站
2022-07-11 09:39:43
1.使用ImageFormatConvertHelper 2.使用VerifyCodeHelper 3.调用方式 返回Code(验证码内容) ......
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(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; } } }
3.调用方式 返回code(验证码内容)
public string getimage() { string code = ""; bitmap bitmap = verifycodehelper.createverifycode(out code); imagesource imagesource = imageformatconverthelper.changebitmaptoimagesource(bitmap); img.source = imagesource; return code; }
上一篇: 昨晚打电话给我姨父
下一篇: 创建索引CreateIndex