首页 > 代码库 > Java 生成验证码
Java 生成验证码
package com.lf.testvity; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sound.midi.Patch; import org.junit.Test; public class Vitiry { //验证码字符的个数 private static int count = 4; //干扰线的条数 private static int lines = 2; /** * 随机产生颜色 * @return 颜色 */ private static Color getRandomColor(){ Random random = new Random(); Color color = new Color(random.nextInt(255)+1, random.nextInt(255)+1, random.nextInt(255)+1); return color; } /** * 获取四个字符的字符串 * @return 字符串 */ public static String getForthWord() { String string = "23456789abcdefghijkmnpqrstuvwxyz"; StringBuilder newStr = new StringBuilder(""); //随机获取count个数字,根据count个随机数产生字符串 Random random = new Random(); for (int i = 0; i < count; i++) { int ranNum=random.nextInt(string.length()); newStr.append(string.charAt(ranNum)); } String str = new String(newStr); return str; } /** * 绘画验证码 * @return BufferedImage */ public static BufferedImage productImage() { int width = 70; int height = 30; // 得到图片缓存区 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 得到它的绘制环境(这张图片的笔) Graphics2D g2 = (Graphics2D)bi.getGraphics(); // 设置颜色 g2.setColor(Color.WHITE); // 填充整张图片(其实就是设置背景颜色) g2.fillRect(0, 0, width, height); // 设置字体 g2.setFont(new Font("宋体", Font.BOLD, 25)); //设置颜色 g2.setColor(Vitiry.getRandomColor()); // 向图片写字符串 g2.drawString(Vitiry.getForthWord(), 7, 25); //画两条干扰线 Random random = new Random(); for (int i = 0; i < lines; i++) { g2.drawLine(2, random.nextInt(height-10)+10, width-5, random.nextInt(height)); } return bi; } }
Java 生成验证码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。