java 实现验证码

时间:2021-02-02 20:40:31
package cn.tedu;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;


import javax.imageio.ImageIO;


public class Demo1 {
public static void main(String[] args) {
int base = 30;
int width = base * 4;
int height = base;
String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
String[] fontNames = { "宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑",
"楷体_GB2312" };


// 1.创建图片缓冲区对象
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);


// 2.得到绘制环境(拿到画笔)
Graphics2D g2 = (Graphics2D) bi.getGraphics();


// 3.开始画图
// drawLine(int x1, int y1, int x2, int y2)
// 在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1) 和 (x2, y2) 之间画一条线。
// g2.drawLine(0, 0, width, height);


// drawOval(int x, int y, int width, int height)
// 绘制椭圆的边框。
// g2.drawOval(0, 0, width, height);
// g2.drawOval(0, 0, height, height);


// drawRect(int x, int y, int width, int height)
// 绘制指定矩形的边框。
// g2.drawRect(0, 0, width-1, height-1);


// fillRect(int x, int y, int width, int height)
// 填充指定的矩形。
g2.fillRect(0, 0, width, height);


// 设置颜色
// g2.setColor(new Color(255, 0, 0));
g2.setColor(Color.RED);


// 设置字体
g2.setFont(new Font("微软雅黑", Font.PLAIN, 22));


// drawString(String str, int x, int y)
// 使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。
for (int i = 0; i < 4; i++) {
String fontName = fontNames[getRandom(0, fontNames.length)];
g2.setFont(new Font(fontName, Font.PLAIN, 22));
g2.setColor(new Color(getRandom(0, 150), getRandom(0, 150),
getRandom(0, 150)));
String code = codes.charAt(getRandom(0, codes.length())) + "";
// -45~+45
int theta = getRandom(-45, +45);
g2.rotate(theta * Math.PI / 180, 7 + i * 30, height - 8);
g2.drawString(code, 7 + i * 30, height - 8);
g2.rotate(-theta * Math.PI / 180, 7 + i * 30, height - 8);


}


for (int i = 0; i < 6; i++) {
g2.setColor(new Color(getRandom(0, 150), getRandom(0, 150),
getRandom(0, 150)));
g2.drawLine(getRandom(0, width), getRandom(0, height),
getRandom(0, width), getRandom(0, height));
}


g2.setColor(Color.GRAY);
g2.drawRect(0, 0, width-1, height-1);


// 4.保存图片
try {
ImageIO.write(bi, "JPEG", new FileOutputStream(
new File("d:/vc.jpg")));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 5.释放资源
g2.dispose();
}


}


public static int getRandom(int start, int end) {
return (new Random().nextInt(end - start) + start);
}
}