1.没什么难度拿过去直接可以使用的,
public class CodeUtil {
private static int width = 100;// 定义图片的宽
private static int height = 35;// 定义图片的高
private static int codeCount = 4;// 定义图片上显示验证码的个数
private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'o', };
private static String [] mFont= {
"仿宋",
"叶根友毛笔行书2.0版",
"宋体",
"微软雅黑",
"新宋体",
"楷体",
"黑体"};
/*
* 获取照片
*/
public static void getImageCode() {
BufferedImage btImage=new BufferedImage
(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics graphicsimage = btImage.getGraphics();
graphicsimage.setColor(getRandomColor());
graphicsimage.setFont(getRandomFont());
graphicsimage.fillRect(0, 0, width, height);
List<int []> xys=getLineXY(5,height,width);
for (int[] is : xys) {
graphicsimage.setColor(getRandomColor());
graphicsimage.drawLine(is[0], is[1], is[2], is[3]);
}
char[] scripts=getRandomScripts(4);
for (int j=0;j<scripts.length;j++) {
graphicsimage.setColor(getRandomColor());
System.out.println(scripts[j]);
graphicsimage.drawString(String.valueOf(scripts[j]),(j + 1) * 17, 27);
}
graphicsimage.dispose();
try {
ImageIO.write(btImage, "jpg", new File("C:AAA.jpg"));//将照片保存在本地
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 获取字体
*/
@Test
public static Font getRandomFont() {
//GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
//String[] fontName = e.getAvailableFontFamilyNames();获取所有的字体,
//for (String string : fontName) {
//System.out.println(string);
//}
int index=getRandomNumber(mFont.length);
System.out.println(mFont[index]);
return new Font(mFont[index],
Font.BOLD, 35);
}
/*
* 获取0-max上面的随机数
*/
public static int getRandomNumber(int max) {
return (int)(Math.random()*(max));
}
/*
* 获取随机颜色
*/
public static Color getRandomColor() {
return new Color(getRandomNumber(255), getRandomNumber(255), getRandomNumber(255));
}
/*
*获取随机子
*/
public static char[] getRandomScripts(int Number) {
char [] cs=new char[4];
for(int i=0;i<Number;i++) {
char ss=codeSequence[getRandomNumber(codeSequence.length-1)];
cs[i]=ss;
}
return cs;
}
/*
* 获取Number条线条坐标
*/
public static List<int[] > getLineXY(int Number,int height,int width){
List<int []> list=new ArrayList<int []>();
for(int i=0;i<Number;i++) {
int [] sy=new int[4];
sy[0]=getRandomNumber(width);
sy[1]=getRandomNumber(height);
sy[2]=getRandomNumber(width);
sy[3]=getRandomNumber(height);
list.add(sy);
}
return list;
}
}