import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import org.junit.Test;
public class ImgDemo {
@Test
public void demo() throws IOException{
int width = 60;
int height = 30;
//该构造方法需要参数:图片的宽高,以及类型
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获得画笔
Graphics g = img.getGraphics();
//给画笔设置颜色
g.setColor(Color.WHITE);
//画背景颜色
g.fillRect(0, 0, width, height);
//设置字体
g.setFont(new Font("qwer", Font.BOLD, 18));
//用来生成随机数
Random r = new Random();
//随机验证码
for(int i = 0; i<4 ; i++){
int a = r.nextInt(10);
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));//随机设置画笔的颜色
g.drawString(""+a, i*16, 10+r.nextInt(20));//画一个随机数
}
//画些干扰线
for(int i = 0;i<18;i++){
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
g.dispose();//相当于IO中的close()方法带动flush()
ImageIO.write(img, "JPEG", new FileOutputStream("d:/hello2.jpg"));
}
}JavaEE——验证码
最新推荐文章于 2021-02-16 19:50:15 发布
2036

被折叠的 条评论
为什么被折叠?



