java生成随机验证码
用到的主要类: Random 生成随机数 BufferedImage 图片缓冲区 Graphics2D 画笔 ImagerIO(RenderedImage image,String formatName,outputStream os) Color new Color(int r,int g,int b) Font new Font(String name, int style, int size) 根据指定名称、样式和磅值大小,创建一个新 Font。
import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; /* * 生成随机验证码 */ public class VerifiCode { private int width = 60; //图片宽度 private int height = 25; //图片高度 private Random rm = new Random(); private String text; //验证码文本 private String codes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";//验证码 private String[] fontNames = {"宋体","华文楷体", "黑体", "微软雅黑", "楷体_GB2312"}; //字体名称 /* *获取随机字体 */ public Font randomFont(){ int style = rm.nextInt(4); //字体样式:0是无样式,1是加粗,2是斜体,3是加粗加斜体 int size = rm.nextInt(4)+20; //字体大小 int index = rm.nextInt(fontNames.length); String fontName = fontNames[index]; Font font = new Font(fontName,style,size); return font; } /* * 获取随机颜色 */ public Color randomColor(){ int r = rm.nextInt(150); int g = rm.nextInt(150); int b = rm.nextInt(150); Color color = new Color(r,g,b); return color; } /* *对验证码图片画干扰线,防止暴力破解 */ public BufferedImage drawLine(BufferedImage image){ Graphics2D g = image.createGraphics(); for(int i=0;i<3;i++){ //三条干扰线 int x1 = rm.nextInt(width); int y1 = rm.nextInt(height); int x2 = rm.nextInt(width); int y2 = rm.nextInt(height); g.drawLine(x1,y1,x2,y2); } return image; } /* *生成验证码图片 */ public BufferedImage drawImage(){ BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { int index = rm.nextInt(codes.length()); String s= codes.charAt(index)+""; sb.append(s); float x = 1.0f*width/5*(i+1); g.setFont(randomFont()); g.setColor(randomColor()); g.drawString(s,x,height-5); } this.text = sb.toString(); drawLine(image); return image; } public String getText() { return text; } public static void input(BufferedImage image,OutputStream os) throws IOException{ ImageIO.write(image,"JPEG",os); //将获取的image写入到输出流os中 } }