Java生成图片验证码
1、编写代码
copy 下面的代码 并运行main函数
import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.util.Base64;import java.util.Random;public class GenericImage {public static void main(String[] args) throws IOException {// 生成4位验证码String verity = genVerityText(4);// 生成验证图片的base64加密字符串String accountName = verityImage(verity);System.out.println(accountName);}public static String verityImage(String verity) throws IOException {Color color = new Color(255,255,255);// 图片的宽度 30 px 像素int width = 90;// 图片高度 30 px 像素int height = 30;// 使用的颜色类型 RGBint imageType = 1;BufferedImage bufferedImage = new BufferedImage(width, height, 1);Graphics graphics = bufferedImage.getGraphics();// 背景色设为白色graphics.setColor(new Color(255, 255, 255));// 背景填充大小graphics.fillRect(0, 0 , width, height);// 添加干扰线addDisturbLine(graphics, width, height, 3);// 绘画验证码drawVerity(graphics, verity, height);graphics.dispose();ByteArrayOutputStream out = new ByteArrayOutputStream();ImageIO.write(bufferedImage, "jpeg", out);// 使用base64进行加密return Base64.getEncoder().encodeToString(out.toByteArray());}public static void addDisturbLine(Graphics graphics, int width, int height, int lineCount){if(lineCount > 0){int x = 0, y, x1 = width, y1;Random random = new Random();for (int i = 0; i < lineCount; i ++){// 随机颜色graphics.setColor(randomColor());y = random.nextInt(height);y1 = random.nextInt(height);// 画线条graphics.drawLine(x, y, x1, y1);}}}public static String genVerityText(int length){StringBuilder verity = new StringBuilder();Random random = new Random();int i = 0;while (i < length){int rand = random.nextInt(10);verity.append(rand);i ++;}return verity.toString();}public static void drawVerity(Graphics graphics, String verity, int height){// 字体大小为图片高度的80%int fsize = (int) (height * 0.8);int fx = height - fsize;int fy = fsize;// 设定字体graphics.setFont(new Font("Default", Font.PLAIN, fsize));// 写验证码字符for (int i = 0; i < verity.length(); i++) {fy = (int)((Math.random() * 0.3 + 0.6) * height);// 随机颜色graphics.setColor(randomColor());// 将验证码字符显示到图象中graphics.drawString(verity.charAt(i) + "", fx, fy);fx += fsize * 0.9;}}private static Color randomColor(){Random random = new Random();return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));}}
2、创建html文件
注意:img 标签的src的值为“data:image/jpeg;base64,”加上main函数输出的内容
<html><head><title>验证码</title></head><body><img style="width: 190px; height: 130px; " src="https://img-/202700552259467.jpeg"></body></html>
3、用浏览器打开html文件
内容如下