[代码] [Java]代码 /** * */ package org.mspring.platform.utils; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOE http://www.szhaoexport.com/linked/20130311.do xception; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; /** * @author Gao Youbo * @since Feb 20, 2012 */ public class ImageUtils { /** * 生成随机验证码 * * @param outputStream * 输出流 * @param allowValidateString * 答应验证码中呈现的字符串 * @return */ public static String validateCode(OutputStream outputStream, String allowValidateString) { int width = 60; int height = 20; BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 缓冲区Image Graphics2D g = buffImg.createGraphics(); // 取得在缓冲区Image中担任绘画的目标(画笔)他是Graphics的字类型 // 创立一个随机数生成器类。 Random random = new Random(); g.setColor(Color.decode("#ffffff")); g.fillRect(0, 0, width, height); // 画一个填充的矩形布景色彩为白色 // 创立字体,字体的巨细大概依据图画的高度来定。 Font font = new Font("Times New Roman", Font.PLAIN, 18); // 设置字体。 g.setFont(font); // 画边框。 // g.setColor(Color.blue); // g.drawRect(0, 0, width - 1, height - 1); // 随机发生160条搅扰线,使图象中的认证码不易被其它程序探测到。 g.setColor(Color.GRAY); for (int i = 0; i < 80; i ) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x xl, y yl); } // randomCode用于保管随机发生的验证码,以便用户登陆后进行验证。 StringBuffer randomCode = new StringBuffer(); int red = 0, green = 0, blue = 0; // 随机发生验证码。 for (int i = 0; i < 4; i ) { // 获得随机发生的验证码数字。 int randomIndex = random.nextInt(allowValidateString.length()); if (randomIndex == 0) randomIndex = 1; String strRand = allowValidateString.substring(randomIndex - 1, randomIndex); // 发生随机的色彩重量来结构色彩值,这样输出的每位数字的色彩值都将不同。 red = random.nextInt(110); green = random.nextInt(50); blue = random.nextInt(50); // 用随机发生的色彩将验证码制做到图画中。 g.setColor(new Color(red, green, blue)); g.drawString(strRand, 13 * i 6, 16); // 将发生的四个随机数组合在一块儿。 randomCode.append(strRand); } try { ImageIO.write(buffImg, "jpeg", outputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return randomCode.toString(); } } http://www.fpfuzhou.com/linked/20130311.do