package com.mypro.api.controller; import com.mypro.api.model.ReturnNode; import com.mypro.api.util.RedisUtils; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; @RestController @RequestMapping("/api/code") public class CheckCodeController { @Resource private RedisUtils redisUtils; @ApiOperation("获取图形验证码") @PostMapping("/getCodeImg") public ReturnNode getCodeImg() throws IOException { int width = 100; int height = 30; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 20)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; 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); } ///画数字 String randomNum = ((int)(Math.random() * (10000))+1000)+""; g.setColor(Color.BLACK); // 设置字体颜色为黑色 Font font = new Font("Arial", Font.PLAIN, 28); // 创建一个字体对象,设置字体为Arial粗体,大小为60像素 g.setFont(font); // 将字体设置为指定的字体 g.drawString(randomNum, 15, 25); // 在图像上绘制数字字符串 ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "png", os); // 将BufferedImage转换为PNG格式的字节数组 byte[] bytes = os.toByteArray(); // 将字节数组转换为byte数组 String base64Str = Base64.getEncoder().encodeToString(bytes); // 将byte数组转换为Base64编码字符串 /写入缓存 String uuidstr = UUID.randomUUID().toString(); String key = "imgcheckcode_"+uuidstr; redisUtils.set(key,randomNum); Map<String,String> result = new HashMap<>(); result.put("base64Str",base64Str); result.put("checkImgId",uuidstr); return ReturnNode.ReturnSuccess(result); } private static Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } }
生成效果: