一、前言
通过java.awt.Graphics2D类绘画平面图形、com.sun.image.codec.jpeg.JPEGCodec压缩图像类,进行随机生成字符串、生成4个字符的验证码图片方法代码示例。
二、代码示例
import java.awt.Color;@b@import java.awt.Font;@b@import java.awt.Graphics2D;@b@import java.awt.image.BufferedImage;@b@import java.io.ByteArrayOutputStream;@b@import java.io.IOException;@b@import java.util.Random;@b@@b@import com.sun.image.codec.jpeg.JPEGCodec;@b@@b@/**@b@ * 随机生成验证码图片@b@ */@b@public class RandomImageGenerator {@b@ /**@b@ * 随机生成字符串@b@ * */@b@ public static String random(int sum) {@b@ String result = "";@b@ String str = "23456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";@b@ Random r = new Random();@b@ while (true) {@b@ if (result.length() == sum) {@b@ break;@b@ }@b@ int index = r.nextInt(str.length());@b@ result += str.charAt(index);@b@ }@b@ return result;@b@ }@b@@b@ /**@b@ * 生成4个字符的验证码图片(90*30,jpg)@b@ * */@b@ public static byte[] render(String num) throws IOException {@b@ if (num.getBytes().length > 4) {@b@ throw new IllegalArgumentException("参数长度只能是4!");@b@ }@b@ // 设定宽度和高度@b@ int width = 90;@b@ int height = 30;@b@ // 在内存中创建图像@b@ BufferedImage bi = new BufferedImage(width, height,@b@ BufferedImage.TYPE_INT_RGB);@b@ //获得图像上下文@b@ Graphics2D g = (Graphics2D) bi.getGraphics();@b@ //画边框@b@ Random r = new Random();@b@ g.setColor(Color.white);//设置背景色@b@ g.fillRect(0, 0, width, height);//绘制矩形边框@b@ //设置字体@b@ Font font = new Font("Tahoma", Font.TYPE1_FONT, 16);@b@ g.setFont(font);@b@ g.setColor(Color.BLACK);//设置字体颜色@b@ //画认证码,每个认证码在不同的水平位置@b@ for(int i = 0; i < num.length(); i++){@b@ String c = num.substring(i, i + 1);@b@ int w = 0;@b@ int x = (i + 1) % 3;@b@ //随机生成认证码的的水平偏移量w@b@ if(x == r.nextInt(3)){@b@ w = 19 - r.nextInt(7);@b@ }else{@b@ w = 19 + r.nextInt(7);@b@ }@b@ //生成随机颜色的文字@b@ Color color = new Color(r.nextInt(180),r.nextInt(180),r.nextInt(180));@b@ g.setColor(color);@b@ g.drawString(c, 20*i+10, w);@b@ }@b@ //随机生成不同颜色的干扰点@b@ for(int i = 0; i < 100; i++){@b@ int x = r.nextInt(width);@b@ int y = r.nextInt(height);@b@ g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));@b@ g.drawOval(x, y, 0, 0);@b@ }@b@ //生成若干随机颜色、随机位置的干扰线@b@ for(int i = 0; i < 5; i++){@b@ //起点坐标(x,y)@b@ int x = r.nextInt(width);@b@ int y = r.nextInt(height);@b@ //终点坐标(x1,y1)@b@ int x1 = r.nextInt(width);@b@ int y1 = r.nextInt(height);@b@ g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));@b@ g.drawLine(x, y, x1, y1);@b@ }@b@ //图像生效@b@ //g.dispose();@b@ ByteArrayOutputStream baop = new ByteArrayOutputStream();@b@ //压缩图像@b@ JPEGCodec.createJPEGEncoder(baop).encode(bi);@b@ //输出图像@b@ //ImageIO.write(bi, "jpg", out);@b@ try {@b@ return baop.toByteArray();@b@ } catch (Exception e) {@b@ throw new RuntimeException(e);@b@ }@b@ }@b@ @b@}