java 生成验证码图片

package Demo;

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

public class yzm {
public static void main(String[] args) {
Random rand = new Random();
//写一个随机生成4为字符串的验证码
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
StringBuffer a = new StringBuffer(4);
for (int i = 0; i < 4; i++) {
char c = str.charAt(rand.nextInt(str.length()));
a.append(c);
}
int w = 160;
int h = 60;
BufferedImage s = new BufferedImage(w, h, 1);
Graphics2D g = s.createGraphics();//开启画笔
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//去锯齿
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
try {
Font f = Font.createFont(Font.TRUETYPE_FONT, new File("C:\Users\86176\Desktop\ADKS____.TTF"));//设置字体
for (int n = 0; n < a.length(); n++) {
Font ff = f.deriveFont(Font.BOLD, rand.nextInt(20) + 35);//设置字体格式和大小
g.setFont(ff);//取得字体
int x = n * 30 + rand.nextInt(20) + 10;
int y = rand.nextInt(10) + 30;
String text = String.valueOf(a.toString().charAt(n));
g.setColor(new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256), rand.nextInt(120) + 100));
g.drawString(text, x, y);//写上验证码
int x1 = 0;//x轴起点
double y1 = 30;//y轴起点
int yy = 30;//y轴的位置
int hh = 30;//上下幅度
int aa = 100;//波动频率
//设置弧线
for (x1 = 10;x1 <= 360;x1++){
y1 = (yy + hh * Math.sin(x1*Math.PI / aa));
g.drawLine(x1,(int)y1,x1,(int)y1);
}
//System.out.println(text);
}
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
g.dispose();
try {
ImageIO.write(s,"jpg",new FileOutputStream("C:\Users\86176\Desktop\ABC.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文地址:https://www.cnblogs.com/liuyunche/p/13821595.html