不多BB,直接看代码
package cn.java.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class YanzhengCode {
//创建生成随机数的对象
public static Random ran = new Random();
public static void main(String[] args) {
FileOutputStream os;
try {
指定你要存放的位置
os = new FileOutputStream("D://xx/xx/xx.png");
CreateNewCode(os);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static String num ;
public static String CreateNewCode(OutputStream os) {
try {
int width = 120;
int height = 50;
//在内存中创建一张图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//绘制这张图片
Graphics pen = image.getGraphics();
//修改底色
pen.setColor(Color.RED);
//进行填充
pen.fillRect(0, 0, width, height);
//携入随机数字 在0——9之间
num = "";
for(int i = 1 ; i <= 4 ;i ++) {
num += ran.nextInt(10);
}
//颜色
pen.setColor(Color.black);
//字体
pen.setFont(new Font("黑体", Font.ITALIC, 35));
//写字
pen.drawString(num, 20, 30);
for(int i = 1 ;i <= 35 ;i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
//画干扰线
pen.setColor(CreateColors());
pen.drawLine(x1, y1, x2, y2);
}
//把图片写入内存
ImageIO.write(image, "png", os);
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
private static Color CreateColors() {
int x1 = ran.nextInt(256);
int x2 = ran.nextInt(256);
int x3 = ran.nextInt(256);
return new Color(x1, x2, x3);
}
}