生成验证码
package thj1;
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 javax.imageio.ImageIO;
public class yanzhengma {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
BufferedImage image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_BGR);
Graphics2D graphics2d = (Graphics2D) image.getGraphics();
graphics2d.setColor(Color.white);// Color类: publib static Color
// black=new Color(0,0,0);
graphics2d.fillRect(0, 0, 200, 80);
// 输出斜线
for (int i = 0; i < 10; i++) {
graphics2d.setColor(randomColor());
graphics2d.drawLine((int) (Math.random() * 200), (int) (Math.random() * 80), (int) (Math.random() * 200),
(int) (Math.random() * 80));
}
// 输出字母或数字
for (int i = 0; i < 4; i++) {
graphics2d.setColor(randomColor());
graphics2d.setFont(new Font("宋体", Font.BOLD, 40));
graphics2d.drawString(String.valueOf(randomChar()), i * 50 + 20, (int) (Math.random() * 1000 % 40 + 40));
}
ImageIO.write(image, "JPEG", new FileOutputStream(new File("F:yanzhengma.jpg")));
System.out.println("输出完成");
}
// 生成随机颜色
public static Color randomColor() {
int i = (int) (Math.random() * 10000) % 256;
int j = (int) (Math.random() * 10000) % 256;
int k = (int) (Math.random() * 10000) % 256;
return new Color(i, j, k);
}
// 生成输入随机字符
public static char randomChar() {
String s = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
int i = (int) (Math.random() * 1000 % 62);
return s.charAt(i);
}
}