Skip to content

输出图片验证码 #17

@bitfishxyz

Description

@bitfishxyz
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;

public class Draw {
    private static final char[] alps = "ABCDeFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();

    @Test
    public void draw() throws Exception{
        // 用来绘图的对象
        BufferedImage bufferedImage = new BufferedImage(68, 22,
                BufferedImage.TYPE_INT_BGR);

        // 拿到画笔
        Graphics graphics = bufferedImage.getGraphics();

        // 设置画笔颜色
        graphics.setColor(new Color(255, 255, 255));

        // 绘制背景色
        graphics.fillRect(0,0,68,22);

        Random random = new Random();

        // 用于记录随机生成的验证码
        StringBuilder verificationCode = new StringBuilder();

        // 一个生成四个随机数
        for (int i = 0; i < 4; i++) {
            // 设置一个随机颜色
            graphics.setColor(new Color(random.nextInt(125),
                    random.nextInt(125), random.nextInt(125)));

            // 生成一个随机字符
            String alp = alps[random.nextInt(alps.length)] + "";

            // 将字符输出到图片上,注意让字符之间有间隔
            graphics.drawString(alp, i * 15 + 3, 18);

            verificationCode.append(alp);
        }

        // 将图片输出到文件系统
        OutputStream os = new FileOutputStream("./aa.jpg");
        ImageIO.write(bufferedImage, "JPG", os);

        System.out.println(verificationCode.toString());
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions