JavaEE——验证码

来源:互联网 发布:苹果young网络客户端 编辑:程序博客网 时间:2024/06/13 06:54
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 {@Testpublic 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"));}}

1 0
原创粉丝点击