JavaEE——验证码

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"));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值