菜鸟时期的.net笔记[纯代码,慎入]

4次阅读

个人理解均在注释中,欢迎多提意见哈,共勉。 正文 1. 生成验证码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Drawing;using System.Drawing.Imaging;using System.IO;namespace ConsoleApplication4{
class DrawingHelper
{
private string CreateCheckCodeString()
{
// 定义用于验证码的字符数组
char[] allCharArray = { '0', '1', '2', '3', '4', '5', '6', '7', 'a', 'b', 'c', 'd', 'e', 'f'};
// 定义验证码字符串
string randomCode = "";
Random rand = new Random();
// 生成 4 位验证码字符串
for (int i = 0; i < 4; i++)
randomCode += allCharArray[rand.Next(allCharArray.Length)];
return randomCode;
}
// 生成验证码图片
public void CreateCheckCodeImage(string sFilePath)
{
// 定义图片的宽度
int iWidth = 55;
// 定义图片的高度
int iHeight = 22;
// 定义大小为 12pt 的 Arial 字体,用于绘制文字
Font font = new Font("Arial", 12, FontStyle.Bold);
// 定义黑色的单色画笔,用于绘制文字
SolidBrush brush = new SolidBrush(Color.Black);
// 定义钢笔,用于绘制干扰线
Pen pen1 = new Pen(Color.Gray, 0);// 注意这里直接获得了一个现有的 Color 对象
Pen pen2 = new Pen(Color.FromArgb(255, 100, 100, 100), 0);// 注意这里根据 ARGB 值获得了一个 Color 对象
// 创建一个 55*22px 的图像
Bitmap image = new Bitmap(iWidth, iHeight);
// 从图像获取一个绘图面
Graphics g = Graphics.FromImage(image);
// 清楚整个绘图画面并以指定颜色填充
g.Clear(ColorTranslator.FromHtml("#f0f0f0"));// 注意这里从 HTML 颜色代码获得了 Color 对象
// 定义文字的绘制矩形区域
RectangleF rect = new RectangleF(5, 2, iWidth, iHeight);
// 定义一个随机数对象,用于绘制干扰线
Random rand = new Random();
// 生成两条横向的干扰线
for (int i = 0; i < 2; i++)
{
// 定义起点
Point p1 = new Point(0, rand.Next(iHeight));
// 定义终点
Point p2 = new Point(iWidth, rand.Next(iHeight));
// 绘制直线
g.DrawLine(pen1, p1, p2);
}
// 生成 4 条纵向的干扰线
for (int i = 0; i < 2; i++)
{
// 定义起点
Point p1 = new Point(rand.Next(iWidth), 0);
// 定义终点
Point p2 = new Point(rand.Next(iWidth), iHeight);
// 绘制直线
g.DrawLine(pen2, p1, p2);
}
// 绘制验证码文字
g.DrawString(CreateCheckCodeString(), font, brush, rect);
// 保存图片为 JPEG 格式
image.Save(sFilePath, ImageFormat.Jpeg);
// 释放对象
g.Dispose();
image.Dispose();
}}
class Program
{
static void Main(string[] args)
{
// 测试代码:
DrawingHelper dh = new DrawingHelper();
dh.CreateCheckCodeImage(@"D:/C#/CheckCode.jpg");
}
}}

正文完