package com.hx.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; import javax.imageio.ImageIO; /** * 验证码生成器 * @author ChenJiaHe * @Date 2020-06-17 */ public class CheckCodeImageUtil { private final static int WIDTH = 60; private final static int HEIGHT = 20; private static char[] generateCheckCode() { // ������֤����ַ�� String chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char[] rands = new char[4]; for (int i = 0; i < 4; i++) { int rand = (int) (Math.random() * 35); rands[i] = chars.charAt(rand); } return rands; } private static void drawRands(Graphics g, char[] rands) { g.setColor(Color.BLACK); g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18)); // �ڲ�ͬ�ĸ߶��������֤���ÿ���ַ� g.drawString("" + rands[0], 1, 17); g.drawString("" + rands[1], 16, 15); g.drawString("" + rands[2], 31, 18); g.drawString("" + rands[3], 46, 16); } private static void drawBackground(Graphics g) { // ������ g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, WIDTH, HEIGHT); // ������120�����ŵ� for (int i = 0; i < 120; i++) { int x = (int) (Math.random() * WIDTH); int y = (int) (Math.random() * HEIGHT); int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); g.setColor(new Color(red, green, blue)); g.drawOval(x, y, 1, 0); } } public static String[] createImage(String id) { ByteArrayOutputStream bos = null; String reStr = ""; char[] rands = null; try { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); rands = generateCheckCode(); drawBackground(g); drawRands(g, rands); g.dispose(); bos = new ByteArrayOutputStream(); ImageIO.write(image, "JPEG", bos); byte[] buf = bos.toByteArray(); reStr = Base64.getEncoder().encodeToString(buf); }catch (Exception e) { e.printStackTrace(); }finally { if(bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } bos = null; } } return new String[] {new String(rands),reStr}; } }