using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Drawing;

namespace
XiaoNei.VerifyImage

...
{
public static class Verify

...{
private static int[,] imageDatas;
private static String code;
private static Bitmap image;


/**//**//**//// <summary>
/// 获取验证码
/// </summary>
/// <param name="filename">输入文件名</param>
/// <returns>验证码</returns>
public static String getCode(String filename)

...{
Bitmap image = new Bitmap(filename);
readDatas(image);
code = "" + getBestCode(getSimple(3, 5)) +
getBestCode(getSimple(3, 13)) +
getBestCode(getSimple(3, 21)) +
getBestCode(getSimple(3, 29));
Console.WriteLine(code);

//测试识别是否正确,文件名中含有验证码
//if (filename.IndexOf(code) < 0)
// Console.WriteLine("Error");
return code;
}


/**//**//**//// <summary>
/// 初始化数据
/// </summary>
private static void readDatas(Bitmap image)

...{

imageDatas = new int[image.Height, image.Width];
Color pixelColor;
for (int h = 0; h < image.Height; h++)

...{
for (int w = 0; w < image.Width; w++)

...{
pixelColor = image.GetPixel(w, h);

imageDatas[h, w] = pixelColor.R > 0 ? 1 : 0;
}//for
}//for
}

/**//**//**//// <summary>
/// 取数字块
/// </summary>
/// <param name="x">横坐标</param>
/// <param name="y">纵坐标</param>
/// <returns>一维数组</returns>
private static int[] getSimple(int x, int y)

...{
int[] simple = new int[9 * 6];
int count = 0;
for (int h = x; h < x + 9; h++)

...{
for (int w = y; w < y + 6; w++)

...{
simple[count++] = imageDatas[h, w];
}
}
return simple;
}

/**//**//**//// <summary>
/// 最和谐的数字
/// </summary>
/// <param name="x">数字块</param>
/// <returns>结果</returns>
private static int getBestCode(int[] x)

...{
int bestNumber = -1;
double bestVal = 0.0;
for (int index = 0; index < 10; index++)

...{
double val = compareSimple(NumberData.getNumber(index), x);
if (bestVal <= val)

...{
bestVal = val;
bestNumber = index;
}
}
return bestNumber;
}

/**//**//**//// <summary>
/// 获取两个数字图像数组的和谐百分比
/// </summary>
/// <param name="t">匹配数字数组</param>
/// <param name="x">待匹配数字数组</param>
/// <returns>和谐百分比</returns>
private static double compareSimple(int[] t, int[] x)

...{
int count = 0;
int val = 0;
for (int i = 0; i < t.Length; i++)

...{
if (1 == t[i])

...{
count++;
if (1 == x[i])

...{
val++;
}
}
}
return (val + 0.0) / count;
}
}


}

最近在做一个校内刷人气的小工具,顺便把图像识别搞了一下。 把源代码贴出来。请高手指教。