日期:2014-05-16  浏览次数:20733 次

C#获取验证码
我现在有一个类用来生产验证码图片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Drawing;

/// <summary>
///random 的摘要说明
/// </summary>
public class random
{    private HttpResponse Response;
     public random(HttpResponse Response)
{
        this.Response = Response;
    }
    
    //创建由4位随机数字组成的字符串
    public  StringBuilder four_random() {

        StringBuilder str=new StringBuilder();
        System.Random my_random=new Random();
      
        for (int i = 0; i < 4; i++) {

            str.Append((my_random.Next()%10).ToString());
            }
        //Session["yzm"] = str.ToString();
        return str;
   }
    //创建图片
    public void createImage(StringBuilder str) {

        if (str == null || str.ToString().Trim() == string.Empty) {
            return;      
        }

        System.Drawing.Bitmap image = new System.Drawing.Bitmap(str.Length*12,20);  //创建位图 指定宽和高

        Graphics g = Graphics.FromImage(image);  //system.drawing  建立画布

        Random random = new Random();

        g.Clear(Color.White); //清空画布 用白色填充

        //背景噪音线
        for (int i = 0; i < 10; i++) {
            //指定坐标
            int x1 = random.Next(image.Width);
            int x2 = random.Next(image.Width-i);
            int y1 = random.Next(image.Height);
            int y2 = random.Next(image.Height);
            //画线
            g.DrawLine(new Pen(Color.Red),x1,y1,x2,y2);
        }

        Font font = new Font("Arial",12,(FontStyle.Bold|FontStyle.Italic));//字体倾斜加粗

        System.Drawing.Drawing2D.LinearGradientBrush br