1 import java.awt.Color; 2 import java.awt.Font; 3 import java.awt.FontMetrics; 4 import java.awt.Graphics2D; 5 import java.awt.image.BufferedImage; 6 import java.io.File; 7 import java.io.IOException; 8 import java.util.Random; 9 10 import javax.imageio.ImageIO; 11 12 public class Test { 13 14 /** 15 * @param args 16 * @throws IOException 17 */ 18 public static void main(String[] args) throws IOException { 19 //用于随机生成验证码的字符串集 20 String[] strs = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R" 21 ,"S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j" 22 ,"k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1" 23 ,"2","3","4","5","6","7","8","9"}; 24 //随机生成干扰线的纵坐标y1和y2 25 Random y1Random = new Random(); 26 Random y2Random = new Random(); 27 int y1 = y1Random.nextInt(31); 28 int y2 = y2Random.nextInt(31); 29 30 //随机生成用于组成验证码的字符串所在集的下标值 31 Random code1Random = new Random(); 32 Random code2Random = new Random(); 33 Random code3Random = new Random(); 34 Random code4Random = new Random(); 35 int code1Index = code1Random.nextInt(62); 36 int code2Index = code2Random.nextInt(62); 37 int code3Index = code3Random.nextInt(62); 38 int code4Index = code4Random.nextInt(62); 39 40 //随机生成rgb颜色 41 Random rRandom = new Random(); 42 Random gRandom = new Random(); 43 Random bRandom = new Random(); 44 int r = rRandom.nextInt(256); 45 int g = gRandom.nextInt(256); 46 int b = bRandom.nextInt(256); 47 Color color = new Color(r, g, b); 48 49 //拼接成完整字符串 50 String codeString = strs[code1Index] + strs[code2Index] + strs[code3Index] + strs[code4Index]; 51 52 //定义一个宽70像素,高30像素的jpg图片 53 BufferedImage bi = new BufferedImage(70, 30, BufferedImage.TYPE_INT_RGB); 54 //定义graphis绘画对象 55 Graphics2D graphics2d = bi.createGraphics(); 56 graphics2d.setBackground(Color.WHITE); 57 graphics2d.setColor(color); 58 graphics2d.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20)); 59 graphics2d.clearRect(0, 0, 70, 30);
//绘制干扰线 60 graphics2d.drawLine(0, y1, 70, y2); 61 62 //居中绘制字符串 63 FontMetrics fontMetrics = graphics2d.getFontMetrics(); 64 int stringWidth = fontMetrics.stringWidth(codeString); 65 int stringAscent = fontMetrics.getAscent(); 66 int xCode = 70 / 2 - stringWidth / 2; 67 int yCode = 30 / 2 + stringAscent / 2; 68 graphics2d.drawString(codeString, xCode, yCode); 69 70 //输出图片 71 File file = new File("C:\\Users\\zhengbing\\Desktop\\image.jpg"); 72 ImageIO.write(bi, "jpeg", file); 73 } 74 75 }
最后可以返回校验字符串codeString,来达到验证的功能