import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
/**
* @author Mxhlin
* @Email [email protected]
* @Date 2022/09/27/20:48
* @Version
* @Description
*/
public class ZDemo03 {
public static void main(String[] args) throws IOException {
int len = 4;// 设置字母个数
int width = len*26;// 设施图像长度
int height = 50;// 设置图像高度
// 后面让验证码随机获得这里面的字符
String letter = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rand = new Random();
StringBuilder sb = new StringBuilder();
// 创建图形 真彩加透明
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();// 画笔
// 平滑
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
// 天秤背景颜色
g.setColor(new Color(rand.nextInt(26)+220,rand.nextInt(26)+220,rand.nextInt(26)+220));
g.fillRect(0,0,width,height);
// 重新设置画笔颜色
g.setColor(new Color(rand.nextInt(256),rand.nextInt(256),rand.nextInt(256)));
for (int i = 0; i < len; i++) {// 循环验证码次数
// 把letter的随机字符 组成单词
String str = String.valueOf(letter.charAt(rand.nextInt(letter.length())));
sb.append(str);// 添加再sb里面
int x = i*25+5;// 设置x y
int y = 35;
Double aDouble = tiltT(g, x, y);// 倾斜
// 设置字体
g.setFont(new Font("微软雅黑",Font.PLAIN,rand.nextInt(20)+20));
// 添加单词 设置位置
g.drawString(str,x,y);
// 反转一下
g.rotate(-aDouble,x,y);
}
g.dispose();
// 输出 文件格式 设置目录
ImageIO.write(bi,"png",new File("xxx.png"));
Runtime.getRuntime().exec("cmd /k start xxx.png");
}
public static Double tiltT(Graphics2D g,int x,int y){
Random rand = new Random();
double radianPercent = Math.PI * (rand.nextInt(35) / 180D);
if (rand.nextBoolean())
radianPercent = -radianPercent;
g.rotate(radianPercent, x, y);
return radianPercent;
}
}
标签:rand,案例,int,验证码,nextInt,import,new,RenderingHints
From: https://www.cnblogs.com/xhlin/p/16736177.html