package com.verify; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; public class VerifyCode { private static final long serialVersionUID = 1L; private Random random = new Random(); // 伪随机数生成器 private int width = 150; // 缓冲区宽度 private int height = 70; // 缓冲区高度 private int lineNum = 5; // 随机线条数 private int charNum = 5; // 随机字符数 private String base = "abcdefghijklmnopqrstuvwxyz23456789"; // 随机字符 private String text; // 用来保存随机字符 /** * 1.创建图片缓冲区 * 2.得到画笔,设置边界 ,绘制随机线条,随机字符 * 3.将图片写到输出流 */ public void getImage() throws IOException { BufferedImage buff = createBufferedImage(); Graphics g = buff.getGraphics(); setBorder(g); randomChar((Graphics2D) g); randomLine(g); } /** * 生成图片缓冲区 * * @return buff */ public BufferedImage createBufferedImage() { BufferedImage buff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics graphics = buff.getGraphics(); graphics.setColor(Color.gray); graphics.fillRect(0, 0, width, height); return buff; } /** * 设置图片边界 * * @param g */ public void setBorder(Graphics g) { g.setColor(Color.blue); g.drawRect(1, 1, width - 2, height - 2); } /** * 绘制随机线条 * * @param g */ public void randomLine(Graphics g) { g.setColor(randomColor()); for (int i = 0; i < lineNum; i++) { int x1 = random.nextInt(width); int y1 = random.nextInt(height); int x2 = random.nextInt(width); int y2 = random.nextInt(height); g.drawLine(x1, y1, x2, y2); } } /** * 绘制随机字符 * * @param g */ public void randomChar(Graphics2D g) { g.setColor(randomColor()); // 设置颜色 g.setFont(new Font(Font.DIALOG, Font.BOLD, 40)); // 设置字体 StringBuffer sb = new StringBuffer(); int x = 10; int degree = random.nextInt() % 30; // 设置旋转的角度 for (int i = 0; i < charNum; i++) { String str = base.charAt(random.nextInt(base.length())) + ""; //从base中获取随机字符 g.rotate(degree * Math.PI / 180, x, 40); // 将角度换成弧度 g.drawString(str, x, 40); g.rotate(-degree * Math.PI / 180, x, 40); // 消除旋转的弧度 x = x + 25; sb.append(str); //将随机字符添加到缓冲区 } text = sb.toString(); //保存所绘制的随机字符 } /** * 通过伪随机数生成器生成随机的颜色 * * @return Color */ public Color randomColor() { int r = random.nextInt(180); int g = random.nextInt(180); int b = random.nextInt(180); return new Color(r, g, b); } }