java生成图形验证码

图形验证码

package com.pica.cloud.account.account.server.util.captcha;

public interface Generator {

    String generateChars(int size);

}

package com.pica.cloud.account.account.server.util.captcha;

import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.TreeRangeMap;
import org.springframework.stereotype.Component;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Component
public class CaptchaGenerator {

    protected RangeMap<Integer, CaptchaContext> ctxs = TreeRangeMap.create();
    protected List<Generator> gens = new ArrayList();

    class NumberLetterGenerator implements Generator {
        @Override
        public String generateChars(int size) {
            return CaptchaUtil.generateUUIDText(size);
        }
    }

    public CaptchaGenerator() throws FontFormatException, IOException {
        int h = 40;
        ctxs.put(Range.closedOpen(0, h), new CaptchaContext(h * 4, h, (int) (h * 1.2), true));
        h *= 2;
        ctxs.put(Range.closedOpen(h / 2, h), new CaptchaContext(h * 4, h, (int) (h * 1.2), true));
        h *= 2;
        ctxs.put(Range.closedOpen(h / 2, Integer.MAX_VALUE), new CaptchaContext(h * 4, h, (int) (h * 1.2), true));
        gens.add(new NumberLetterGenerator());
    }

    @SuppressWarnings("unused")
    public byte[] createCaptcha(String text, int width, int height) {
        CaptchaContext ctx = ctxs.get(height);
        if (ctx == null) {
            ctx = ctxs.get(0);
        }
        return CaptchaUtil.generateImage(text, ctx);
    }

    public String generateChars(int size) {
        int idx = ThreadLocalRandom.current().nextInt(gens.size());
        Generator gen = gens.get(idx);
        return gen.generateChars(size);
    }

}

package com.pica.cloud.account.account.server.service.impl;

import com.pica.cloud.account.account.server.service.CaptchaService;
import com.pica.cloud.account.account.server.util.MemcachedClientWrapper;
import com.pica.cloud.account.account.server.util.captcha.CaptchaGenerator;
import com.pica.cloud.account.account.server.util.captcha.CaptchaToken;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;

@Component
public class CaptchaServiceImpl implements CaptchaService {

    private final int size = 5;
    private final String CAPTCHA_PREFIX = "captcha-";
    @Autowired
    private CaptchaGenerator agent;
    @Autowired
    MemcachedClientWrapper cache;
	//生成图形验证码
    @Override
    public CaptchaToken generateToken(int width, int height) {
        String origin = agent.generateChars(size);
        byte[] buf = agent.createCaptcha(origin, width, height);
        CaptchaToken ret = new CaptchaToken();
        ret.setBuf(buf);
        ret.setOrigin(origin);
        ret.setToken(DigestUtils.md5Hex(UUID.randomUUID().toString()));
        cache.set(CAPTCHA_PREFIX + ret.getToken(), origin);
        return ret;
    }

    @Override
    public boolean acknowledge(String token, String answer) {
        String origin = cache.get(CAPTCHA_PREFIX + token);
        cache.remove(CAPTCHA_PREFIX + token);
        if (origin != null && answer != null) {
            return origin.compareToIgnoreCase(answer) == 0;
        }
        return false;
    }

}



package com.pica.cloud.account.account.server.util.captcha;

import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Base64;

public class CaptchaToken {

    /**
     * 代表此验证码的唯一标识符,超时和一次使用均会失效
     */
    protected String token;

    /**
     * 代表此验证码的实际图片,以字节码方式提供
     */
    @JsonIgnore
    protected byte[] buf;

    /**
     * 原始随机字符串
     */
    @JsonIgnore
    protected String origin;

    /**
     * base64编码的图片
     */
    protected String content;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public byte[] getBuf() {
        return buf;
    }

    public void setBuf(byte[] buf) {
        this.buf = buf;
        setContent(Base64.getEncoder().encodeToString(this.buf));
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getOrigin() {
        return origin;
    }

    public void setOrigin(String origin) {
        this.origin = origin;
    }
}

package com.pica.cloud.account.account.server.util.captcha;

import org.apache.commons.io.IOUtils;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class CaptchaContext {

    final Random rnd = ThreadLocalRandom.current();
    final int fontCount = 4;

    public int width;
    public int height;
    public float fontSize;
    public boolean showGrid;

    public int gridSize = 1 + rnd.nextInt(10);
    public int rotationAmplitude = rnd.nextInt(10);
    public int scaleAmplitude = 2 * rotationAmplitude;

    public Font font;

    static byte[][] fontDatas = new byte[4][];

    static {
        try {
            InputStream fontStream = CaptchaGenerator.class.getClassLoader().getResourceAsStream("1.ttf");
            fontDatas[0] = IOUtils.toByteArray(fontStream);
            fontStream.close();
            fontStream = CaptchaGenerator.class.getClassLoader().getResourceAsStream("2.ttf");
            fontDatas[1] = IOUtils.toByteArray(fontStream);
            fontStream.close();
            fontStream = CaptchaGenerator.class.getClassLoader().getResourceAsStream("3.ttf");
            fontDatas[2] = IOUtils.toByteArray(fontStream);
            fontStream.close();
            fontStream = CaptchaGenerator.class.getClassLoader().getResourceAsStream("4.ttf");
            fontDatas[3] = IOUtils.toByteArray(fontStream);
            fontStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public CaptchaContext(int width, int height, int fontSize, boolean showGrid) throws FontFormatException, IOException {
        this.width = width;
        this.height = height;
        this.fontSize = fontSize;
        this.showGrid = showGrid;
        int index = ThreadLocalRandom.current().nextInt(0, fontCount);
        this.font = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(fontDatas[index]));
    }

    public int rndGridSize() {
        return 1 + rnd.nextInt(10);
    }

    public int rndRotationAmplitude() {
        return rnd.nextInt(10);
    }

    public int rndScaleAmplitude() {
        return rnd.nextInt(20);
    }

    public float rndFontSize() {
        return fontSize + rnd.nextFloat();
    }

}


package com.pica.cloud.account.account.server.util.captcha;

import org.apache.commons.io.IOUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class CaptchaUtil {

    final static int MAXSIZE = UUID.randomUUID().toString().replace("_", "").length();
    static byte[] imageData;

    static {
        try {
            InputStream imageStream = CaptchaUtil.class.getClassLoader().getResourceAsStream("1.png");
            imageData = IOUtils.toByteArray(imageStream);
            imageStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String generateUUIDText(int count) {
        int pos = count < MAXSIZE ? count : MAXSIZE;
        pos = pos <= 0 ? 5 : pos;
        return UUID.randomUUID().toString().replace("_", "").substring(0, pos);
    }

    public static byte[] generateImage(String text, CaptchaContext ctx) {
        byte[] ret = null;
        try {
            BufferedImage img = createCaptcha(text, ctx);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(img, "png", baos);
            baos.flush();
            ret = baos.toByteArray();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static BufferedImage createCaptcha(String src, CaptchaContext ctx) throws IOException{
        char[] text = src == null ? new char[0] : src.toCharArray();
        if (text == null || text.length == 0) {
            throw new IllegalArgumentException("No captcha text given");
        }

        //BufferedImage image = new BufferedImage(ctx.width, ctx.height, BufferedImage.TYPE_INT_RGB);
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));
        Graphics2D g2d = image.createGraphics();
        //g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //g2d.setBackground(Color.WHITE);
        g2d.setColor(Color.BLACK);

        Stroke s = new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
        Line2D line = new Line2D.Double(5,60,600,140);
        g2d.draw(line);

        //clearCanvas(g2d, ctx);
        //if (ctx.showGrid) {
        //    drawGrid(g2d, ctx);
        //}

        ctx.height = image.getHeight();
        int charMaxWidth = (int) ((image.getWidth() * 0.8) / text.length);
        int xPos = (int) (image.getWidth() * 0.1);
        for (char ch : text) {
            drawCharacter(g2d, ctx, ch, xPos, charMaxWidth);
            xPos += charMaxWidth;
        }

        g2d.dispose();

        return image;
    }

    /**
     * Clears the canvas.
     */
    private static void clearCanvas(Graphics2D g2d, CaptchaContext ctx) {
        g2d.clearRect(0, 0, ctx.width, ctx.height);
    }

    /**
     * Draws the background grid.
     */
    private static void drawGrid(Graphics2D g2d, CaptchaContext ctx) {
        for (int y = 2; y < ctx.height; y += ctx.gridSize) {
            g2d.drawLine(0, y, ctx.width - 1, y);
        }

        for (int x = 2; x < ctx.width; x += ctx.gridSize) {
            g2d.drawLine(x, 0, x, ctx.height - 1);
        }
    }

    /**
     * Draws a single character.
     *
     * @param g2d {@link Graphics2D} context
     * @param ch character to draw
     * @param x left x position of the character
     * @param boxWidth width of the box
     */
    private static void drawCharacter(Graphics2D g2d, CaptchaContext ctx, char ch, int x, int boxWidth) {
        ThreadLocalRandom rnd = ThreadLocalRandom.current();
        double degree = (rnd.nextDouble() * ctx.rndRotationAmplitude() * 2) - ctx.rndRotationAmplitude();
        double scale = 1 - (rnd.nextDouble() * ctx.rndScaleAmplitude() / 100);

        Graphics2D cg2d = (Graphics2D)g2d.create();
        cg2d.setFont(ctx.font.deriveFont(ctx.rndFontSize()));

        cg2d.translate(x + (boxWidth / 2), ctx.height / 2);
        cg2d.rotate(degree * Math.PI / 90);
        cg2d.scale(scale, scale);

        FontMetrics fm = cg2d.getFontMetrics();
        int charWidth = fm.charWidth(ch);
        int charHeight = fm.getAscent() + fm.getDescent();

        cg2d.drawString(String.valueOf(ch), -(charWidth / 2), fm.getAscent() - (charHeight / 2));

        cg2d.dispose();
    }

}

图片和字体资源:
在这里插入图片描述
1.ttf 2.ttf 3.ttf 4.ttf 为字体文件根据自己需要去下载(系统字体在c:\window\Fonts下)

<!doctype html>
<html>
	<head><title>图形验证码</title></head>
	<body style="text-align: center;margin-top:300px;">
		<img id="imgOb" width="90" height="25" onclick="onclick2(this)"/>
	</body>
	
	<script>
		function onclick2(imgObj){
			xmlHttp = new XMLHttpRequest();
			xmlHttp.open("GET","http://localhost:13201/account/account/captcha");
			xmlHttp.send() ;  
			xmlHttp.onreadystatechange = function() {
				if(this.readyState == 4 && this.status === 200){
					//console.log(this.responseText)
					var obj = JSON.parse(this.responseText);
					imgObj.src="data:image/png;base64,"+obj.data.content;
				}
			};
		}
		window.onload=onclick2(document.getElementById('imgOb'));

	</script>
</html>

拼图码


// Copyright 2016-2101 Pica.
package com.pica.cloud.proof.server.service.impl;

import com.pica.cloud.foundation.redis.ICacheClient;
import com.pica.cloud.proof.contract.request.SliderImageRequest;
import com.pica.cloud.proof.server.configuration.BeanConfiguration;
import com.pica.cloud.proof.server.service.SliderService;
import com.pica.cloud.proof.server.util.Constants;
import com.pica.cloud.proof.server.util.VerifyImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class SliderServiceImpl implements SliderService {

    protected static Logger logger = LoggerFactory.getLogger(SliderServiceImpl.class);

    @Autowired
    private ICacheClient iCacheClient;

    @Autowired
    private BeanConfiguration beanConfiguration;

    @Override
    public Map getPica() {
        try {
            // 随机选择需要切的图
            int randNum = new Random().nextInt(2) + 1;
            String targetImgUrl = beanConfiguration.getFILE_URL() + Constants.SLIDER_IMAGE_TARGETS + randNum + ".png";
            logger.info("SliderServiceImpl/getPica:targetImgUrl: " + targetImgUrl);
            URL targetFile = new URL(targetImgUrl);

            // 随机选择剪切模版
            int num = new Random().nextInt(1) + 1;
            String temImgUrl = beanConfiguration.getFILE_URL() + Constants.SLIDER_IMAGE_TEMPLATES + num + "-w.png";
            logger.info("SliderServiceImpl/getPica:temImgUrl: " + temImgUrl);
            URL tempImgFile = new URL(temImgUrl);

            // 根据模板裁剪图片
            Map<String, Object> resultMap = VerifyImageUtil.pictureTemplatesCut(tempImgFile, targetFile);
            // 生成流水号,这里就使用时间戳代替
            String lno = Calendar.getInstance().getTimeInMillis() + "";

            iCacheClient.set(lno, Integer.valueOf(resultMap.get("xWidth") + ""), 60);

            resultMap.put("capcode", lno);
            // 移除横坐标送前端
            resultMap.remove("xWidth");
            return resultMap;
        } catch (Exception e) {
            logger.info("SliderServiceImpl/getPica: error: {}", e);
            return null;
        }
    }

    @Override
    public Map checkcapcode(SliderImageRequest request) {

        int xpos = request.getXpos();
        Map<String, Object> result = new HashMap<String, Object>();
        Integer x = iCacheClient.get(request.getCapcode(), Integer.class);
        if (x == null) {
            // 超期
            result.put("code", 3);
        } else if (xpos - x > 5 || xpos - x < -5) {
            // 验证失败
            result.put("code", 2);
            //  加入百分比验证
            percentCompare(request, xpos, x , result);
        } else {
            // 验证成功
            result.put("code", 1);
            // .....做自己的操作,发送验证码
        }

        return result;
    }
    
	/**
     * @Description 百分比验证
     * @Author Chongwen.jiang
     * @Date 2020/4/2 12:26
     * @ModifyDate 2020/4/2 12:26
     * @Params [request, xpos, result]
     * @Return void
     */
    private void percentCompare(SliderImageRequest request, int xpos, int x, Map<String, Object> result) {
        if (request.getClientBackImageWidth() > 0) {
            //  h5端加入百分比验证
            String key = Constants.ORIGINAL_BACK_IMG_WIDTH_KEY.replace("{timestamp}", request.getCapcode());
            if (iCacheClient.exists(key)) {
                BigDecimal x2 = new BigDecimal(x);
                BigDecimal clientXpos = new BigDecimal(xpos);
                BigDecimal originalWidth = new BigDecimal(iCacheClient.get(key));
                BigDecimal clientBackImageWidth = new BigDecimal(request.getClientBackImageWidth());

                BigDecimal originalPercent = x2.divide(originalWidth, 3, BigDecimal.ROUND_HALF_UP);
                BigDecimal clientPercent = clientXpos.divide(clientBackImageWidth, 3, BigDecimal.ROUND_HALF_UP);
                BigDecimal resultPercent = clientPercent.subtract(originalPercent);
                logger.info("percentCompare-xpos:{}, originalPercent:{}, clientPercent:{}, resultPercent:{}",
                        xpos, originalPercent, clientPercent, resultPercent);
                BigDecimal max = new BigDecimal(0.025);
                BigDecimal min = new BigDecimal(-0.025);
                if (resultPercent.compareTo(min) >= 0 && resultPercent.compareTo(max) <= 0) {
                    // 验证成功
                    result.put("code", 1);
                }
            }
        }
    }

}

package com.pica.cloud.proof.server.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class VerifyImageUtil {

    private static Logger log = LoggerFactory.getLogger(VerifyImageUtil.class);

    private static int BOLD = 5;

    private static final String IMG_FILE_TYPE = "jpg";

    private static final String TEMP_IMG_FILE_TYPE = "png";

    /**
     * 根据模板切图
     *
     * @param templateFile
     * @param targetFile
     * @return
     * @throws Exception
     */
    public static Map < String, Object > pictureTemplatesCut(URL templateFile, URL targetFile) throws Exception {
        Map < String, Object > pictureMap = new HashMap <>();
        // 模板图
        BufferedImage imageTemplate = ImageIO.read(templateFile);
        int templateWidth = imageTemplate.getWidth();
        int templateHeight = imageTemplate.getHeight();

        // 原图
        BufferedImage oriImage = ImageIO.read(targetFile);
        int oriImageWidth = oriImage.getWidth();
        int oriImageHeight = oriImage.getHeight();

        // 随机生成抠图坐标X,Y
        // X轴距离右端targetWidth Y轴距离底部targetHeight以上
        Random random = new Random();
        int widthRandom = random.nextInt(oriImageWidth - 2 * templateWidth) + templateWidth;
        // int heightRandom = 1;
        int heightRandom = random.nextInt(oriImageHeight - templateHeight);
        log.info("原图大小{} x {},随机生成的坐标 X,Y 为({},{})", oriImageWidth, oriImageHeight, widthRandom, heightRandom);

        // 新建一个和模板一样大小的图像,TYPE_4BYTE_ABGR表示具有8位RGBA颜色分量的图像,正常取imageTemplate.getType()
        BufferedImage newImage = new BufferedImage(templateWidth, templateHeight, imageTemplate.getType());
        // 得到画笔对象
        Graphics2D graphics = newImage.createGraphics();
        // 如果需要生成RGB格式,需要做如下配置,Transparency 设置透明
        newImage = graphics.getDeviceConfiguration().createCompatibleImage(templateWidth, templateHeight,
                Transparency.TRANSLUCENT);

        // 新建的图像根据模板颜色赋值,源图生成遮罩
        cutByTemplate(oriImage, imageTemplate, newImage, widthRandom, heightRandom);

        // 设置“抗锯齿”的属性
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setStroke(new BasicStroke(BOLD, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
        graphics.drawImage(newImage, 0, 0, null);
        graphics.dispose();

        ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();// 新建流。
        ImageIO.write(newImage, TEMP_IMG_FILE_TYPE, newImageOs);// 利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。
        byte[] newImagebyte = newImageOs.toByteArray();

        ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();// 新建流。
        ImageIO.write(oriImage, TEMP_IMG_FILE_TYPE, oriImagesOs);// 利用ImageIO类提供的write方法,将bi以jpg图片的数据模式写入流。
        byte[] oriImageByte = oriImagesOs.toByteArray();

        pictureMap.put("slidingImage", Base64Utils.encodeToString(newImagebyte));
        pictureMap.put("backImage", Base64Utils.encodeToString(oriImageByte));
        pictureMap.put("xWidth", widthRandom);
        pictureMap.put("yHeight", heightRandom);

        newImageOs.close();
        oriImagesOs.close();

        return pictureMap;
    }

    /**
     * 添加水印
     *
     * @param oriImage
     */
    /*
     * private static BufferedImage addWatermark(BufferedImage oriImage) throws IOException { Graphics2D graphics2D =
     * oriImage.createGraphics(); graphics2D .setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints
     * .VALUE_INTERPOLATION_BILINEAR); // 设置水印文字颜色 graphics2D.setColor(Color.BLUE); // 设置水印文字Font graphics2D.setFont(new
     * java.awt.Font("宋体", java.awt.Font.BOLD, 50)); // 设置水印文字透明度 graphics2D.setComposite
     * (AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f)); // 第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
     * graphics2D.drawString("zhoujin@qq.com", 400,300); graphics2D.dispose(); //释放 return oriImage; }
     */

    /**
     * @param oriImage 原图
     * @param templateImage 模板图
     * @param newImage 新抠出的小图
     * @param x 随机扣取坐标X
     * @param y 随机扣取坐标y
     * @throws Exception
     */
    private static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage,
            int x, int y) {
        // 临时数组遍历用于高斯模糊存周边像素值
        int[][] martrix = new int[3][3];
        int[] values = new int[9];

        int xLength = templateImage.getWidth();
        int yLength = templateImage.getHeight();
        // 模板图像宽度
        for (int i = 0; i < xLength; i++) {
            // 模板图片高度
            for (int j = 0; j < yLength; j++) {
                // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
                int rgb = templateImage.getRGB(i, j);
                if (rgb < 0) {
                    newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j));

                    // 抠图区域高斯模糊
                    readPixel(oriImage, x + i, y + j, values);
                    fillMatrix(martrix, values);
                    oriImage.setRGB(x + i, y + j, avgMatrix(martrix));
                }

                // 防止数组越界判断
                if (i == (xLength - 1) || j == (yLength - 1)) {
                    continue;
                }
                int rightRgb = templateImage.getRGB(i + 1, j);
                int downRgb = templateImage.getRGB(i, j + 1);
                // 描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
                if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0)
                        || (rgb < 0 && downRgb >= 0)) {
                    newImage.setRGB(i, j, Color.white.getRGB());
                    oriImage.setRGB(x + i, y + j, Color.white.getRGB());
                }
            }
        }
    }

    private static void readPixel(BufferedImage img, int x, int y, int[] pixels) {
        int xStart = x - 1;
        int yStart = y - 1;
        int current = 0;
        for (int i = xStart; i < 3 + xStart; i++)
            for (int j = yStart; j < 3 + yStart; j++) {
                int tx = i;
                if (tx < 0) {
                    tx = -tx;

                }
                else if (tx >= img.getWidth()) {
                    tx = x;
                }
                int ty = j;
                if (ty < 0) {
                    ty = -ty;
                }
                else if (ty >= img.getHeight()) {
                    ty = y;
                }
                pixels[current++] = img.getRGB(tx, ty);

            }
    }

    private static void fillMatrix(int[][] matrix, int[] values) {
        int filled = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                x[j] = values[filled++];
            }
        }
    }

    private static int avgMatrix(int[][] matrix) {
        int r = 0;
        int g = 0;
        int b = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                if (j == 1) {
                    continue;
                }
                Color c = new Color(x[j]);
                r += c.getRed();
                g += c.getGreen();
                b += c.getBlue();
            }
        }
        return new Color(r / 8, g / 8, b / 8).getRGB();
    }

    public static void main(String[] args) {

    }
}

使用的图片如下:
1.png
2.png
1-w.png

中文点选验证

// Copyright 2016-2101 Pica.
package com.pica.cloud.account.account.server.util.captcha;

import java.lang.String;
import java.util.List;

/**
 * @ClassName ImageDto
 * @Description
 * @Author Chongwen.jiang
 * @Date 2020/3/26 12:57
 * @ModifyDate 2020/3/26 12:57
 * @Version 1.0
 */
public class ImageDto {
    /** base64编码的图片 */
    private String captchaImg;
    /** 点选文字提示 */
    private String tips;
    /** 点选文字的x和y坐标集合 */
    private List<String> codeList;

    public String getCaptchaImg() {
        return captchaImg;
    }

    public void setCaptchaImg(String captchaImg) {
        this.captchaImg = captchaImg;
    }

    public String getTips() {
        return tips;
    }

    public void setTips(String tips) {
        this.tips = tips;
    }

    public List<String> getCodeList() {
        return codeList;
    }

    public void setCodeList(List<String> codeList) {
        this.codeList = codeList;
    }
    public ImageDto(){}
    public ImageDto(String captchaImg, String tips, List<String> codeList){
        this.captchaImg = captchaImg;
        this.tips = tips;
        this.codeList = codeList;
    }
}

// Copyright 2016-2101 Pica.
package com.pica.cloud.account.account.server.util.captcha;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @ClassName ImageUtils
 * @Description
 * @Author Chongwen.jiang
 * @Date 2020/3/26 12:55
 * @ModifyDate 2020/3/26 12:55
 * @Version 1.0
 */
@Component
public class ImageUtils {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /** 生成汉字的个数 */
    private static Integer[] arr = new Integer[]{1, 2, 3, 4, 5};
    /** 汉字颜色随机范围 */
    private static Color[] colors = {Color.YELLOW, Color.ORANGE, Color.PINK, Color.BLUE, Color.GREEN};

    public static final String UNDER_LINE = "_";

    private static String han = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";

    /**
     * @Description 生成文字点选验证码
     * @Author Chongwen.jiang
     * @Date 2020/3/26 14:22
     * @ModifyDate 2020/3/26 14:22
     * @Params [sourceImgUrl] 背景图片地址
     * @Return com.pica.cloud.account.account.server.util.captcha.ImageDto
     */
    public ImageDto createTextSelectionImg(String sourceImgUrl) {
        try {
            //生成背景图片
            BufferedImage image = ImageIO.read(new URL(sourceImgUrl));
            Graphics graphics = image.getGraphics();
            int width = image.getWidth();
            int height = image.getHeight();

            Font font = new Font("宋体", Font.BOLD, 30);

            StringBuilder sb = new StringBuilder();
            Random random = new Random();

            //转成集合
            List<Integer> intList = Arrays.asList(arr);
            //重新随机排序
            Collections.shuffle(intList);

            //list参数坐标参数 用于校验是否验证通过
            List<String> codeList = new ArrayList();

            int x = 0;
            int y = 0;

            //定义随机1到arr.length某一个字不参与校验
            int num = random.nextInt(arr.length) + 1;

            Set<String> currentCh = new HashSet<>();

            for (int i = 0; i < arr.length; i++) {
                ThreadLocalRandom tlr = ThreadLocalRandom.current();
                // 5个汉字,只点4个
                String ch;
                do {
                    ch = getRandomHan();
                    currentCh.add(ch);
                } while (!currentCh.contains(ch));

                int place = intList.get(i);
                if (place == 1) {
                    x = tlr.nextInt(width / 2) + 10;
                    y = tlr.nextInt(height / 2) + 10;
                }
                if (place == 2) {
                    x = tlr.nextInt(width / 2) + 10;
                    y = tlr.nextInt(height / 2, height - 30);
                }
                if (place == 3) {
                    x = tlr.nextInt(width / 2, width - 30);
                    y = tlr.nextInt(height / 2) + 10;
                }
                if (place == 4) {
                    x = tlr.nextInt(width / 2, width - 30);
                    y = tlr.nextInt(height / 2, height - 30);
                }
                if (place == 5) {
                    x = tlr.nextInt(width / 2 - 10, width / 2 + 10);
                    y = tlr.nextInt(height / 2 - 10, height / 2 + 10);
                }

                //字体颜色
                graphics.setColor(colors[random.nextInt(colors.length)]);
                //设置角度
                AffineTransform affineTransform = new AffineTransform();
                affineTransform.rotate(Math.toRadians(tlr.nextInt(50, 55)), 0, 0);
                Font rotatedFont = font.deriveFont(affineTransform);
                graphics.setFont(rotatedFont);

                graphics.drawString(ch, x, y);

                if (place != num) {
                    sb.append(ch);
                    codeList.add(x + UNDER_LINE + y);
                }
            }

            // 创建顶部图片
            BufferedImage bi = new BufferedImage(image.getWidth(), 25, BufferedImage.TYPE_INT_RGB);
            Graphics gra = bi.getGraphics();
            // 设置背景颜色
            gra.setColor(new Color(255, 255, 255));
            // 填充区域
            gra.fillRect(0, 0, bi.getWidth(), bi.getHeight());

            // 设置文字背景颜色
            String tips = "请依次点击:" + sb;
            Font fontTips = new Font("宋体", Font.BOLD, 16);
            gra.setFont(fontTips);
            gra.setColor(Color.DARK_GRAY);
            gra.drawString(tips, 10, bi.getHeight() / 2 + fontTips.getSize() / 2);

            BufferedImage combined = new BufferedImage(image.getWidth(), image.getHeight() + bi.getHeight(), BufferedImage.TYPE_INT_RGB);

            //合并
            Graphics g = combined.getGraphics();
            g.drawImage(bi, 0, 0, null);
            g.drawImage(image, 0, bi.getHeight(), null);

            //  缓冲的图片转化成base64编码的字符串
            ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();
            ImageIO.write(combined, "png", newImageOs);
            byte[] newImagebyte = newImageOs.toByteArray();
            String captchaImg = Base64Utils.encodeToString(newImagebyte);

            ImageDto vo = new ImageDto(captchaImg, tips, codeList);
            return vo;
        } catch (Exception e) {
            logger.error("createTextSelectionImg error", e);
            return null;
        }
    }

    /**
     * 获取随机中文
     *
     * @return
     */
    public static String getRandomHan() {
        String ch = han.charAt(new Random().nextInt(han.length())) + "";
        return ch;
    }


}


@Autowired
private ImageUtils testUtils;
@GetMapping(value = "/test2")
public PicaResponse test2(@RequestParam(value = "url") String url){

    return PicaResponse.toResponse(testUtils.createTextSelectionImg(url));
}

<!doctype html>
<html>
	<head><title>图形验证码(点选中文)</title></head>
	<body style="text-align: center;margin-top:200px;">
		<img id="imgOb" onclick="onclick2(this)"/>
	</body>
	
	<script>
		function onclick2(imgObj){
			xmlHttp = new XMLHttpRequest();
			xmlHttp.open("GET","http://localhost:13201/account/test2?url=https://test-file.yunqueyi.com/File/sliderimage/targets/2.png");

			xmlHttp.send() ;  
			xmlHttp.onreadystatechange = function() {
				if(this.readyState == 4 && this.status === 200){
					//console.log(this.responseText)
					var obj = JSON.parse(this.responseText);
					imgObj.src="data:image/png;base64,"+obj.data.captchaImg;
				}
			};
		}
		window.onload=onclick2(document.getElementById('imgOb'));

	</script>
</html>

发布了43 篇原创文章 · 获赞 6 · 访问量 12万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览