一、前言

通过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 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐