版权声明:转载请指明出处 https://blog.csdn.net/weixin_42321963/article/details/82251714
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Font font = new Font("微软雅黑", Font.BOLD, 25);
getverfica(100, 100, 10, 50, font);
}
public static void getPositon() {
}
//
public static void getverfica(int width, int height, int positionX, int positionY, Font font) {
BufferedImage img = new BufferedImage(width, height, 1);
Graphics g = img.getGraphics();
g.setFont(font);
int x = positionX;
int y = positionY;
//设置颜色,画边框,可以设置成其他色,但太难看,所以设置成白色
Color color = getColor(true);
g.setColor(Color.white);
g.drawRect(0, 0, width, height);
//设置颜色填充内部,可以设置成其他色,但太难看,所以设置成黑色
color = getColor(true);
g.setColor(Color.BLACK);
g.fillRect(1, 1, width - 2, height - 2);
//四个不同字体的颜色
char[] chars = getString(4);
Random ran = new Random();
for (int i = 0; i < chars.length; i++) {
color = getColor(true);
g.setColor(color);
g.drawString(chars[i] + "", positionX, positionY);
positionX = positionX + 15 + ran.nextInt(10);
positionY = y + ran.nextInt(10);
}
//设置干扰字
chars = getString(50);
for (int i = 0; i < chars.length; i++) {
font = new Font("微软雅黑", Font.BOLD, ran.nextInt(15));
g.setFont(font);
color = getColor(false);
g.setColor(color);
g.drawString(chars[i] + "", positionX, positionY);
positionX = ran.nextInt(width);
positionY = ran.nextInt(height);
}
//设置干扰线
int lineCount=140;
for (int i = 0; i < lineCount; i++) {
color = getColor(false);
g.setColor(color);
g.drawLine(ran.nextInt(width), ran.nextInt(width), ran.nextInt(width), ran.nextInt(width));
}
//写入文件
try {
ImageIO.write(img, "jpg", new File("d:/test/a.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
//用来取得随机颜色,如果b=true,则透明度为1,否则为随机
public static Color getColor(boolean b) {
Random ran = new Random();
int[] col = new int[3];
for (int i = 0; i < 3; i++) {
col[i] = ran.nextInt(255);
}
Color color;
if (b) {
color = new Color(col[0], col[1], col[2], 254);
} else {
//color = new Color(col[0], col[1], col[2], ran.nextInt(255));
color = new Color(col[0], col[1], col[2], ran.nextInt(120));
/*String d = String.format("%.2f", Math.random());
str = "rgba(" + col[0] + "," + col[1] + "," + col[2] + "," + d + ")";*/
}
return color;
}
//得到随机的n个字符
public static char[] getString(int n) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
char chars[] = new char[n];
Random ran = new Random();
for (int i = 0; i < n; i++) {
chars[i] = str.charAt(ran.nextInt(str.length()));
}
for (char a : chars) {
System.out.println(a);
}
return chars;
}
}
结果如下: