servlet实现随即生成验证码图片

package generate.image;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GenImage extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		BufferedImage image=new BufferedImage(120, 25, BufferedImage.TYPE_INT_RGB);//在内存中生成图片
		Graphics2D g=(Graphics2D) image.getGraphics();
		setBackGround(g);
		setBorder(g);
		drawRandomLine(g);
		drawRandomNum(g);
		response.setContentType("image/jpeg");//设置内容格式
		ImageIO.write(image, "jpg", response.getOutputStream());//将图片输出		
	}
	private void drawRandomNum(Graphics2D g) {
		g.setColor(Color.RED);
		Font font=new Font("宋体",Font.BOLD,100);//设置字体
		String str="abcdefghi1234567890jklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		int x=20;
		for(int i=0;i<5;i++){
			int degree = new Random().nextInt()%30;//使字体旋转-30到30度
			char  ch=str.charAt(new Random().nextInt(57));//随机选取字符
			g.rotate(degree*Math.PI/180, x, 20);
			g.drawString(ch+"", x, 20);
			g.rotate(-degree*Math.PI/180, x, 20);
			x+=20;
			}
	}
	//根据随机产生的坐标画随机线
	private void drawRandomLine(Graphics g) {
		g.setColor(Color.BLUE);		
		for(int i=0;i<5;i++){
		int x1=new Random().nextInt(120);
		int y1=new Random().nextInt(25);
		int x2=new Random().nextInt(120);
		int y2=new Random().nextInt(25);
		g.drawLine(x1, y1, x2, y2);
		}
	}
	//设置边框颜色及范围
	private void setBorder(Graphics g) {
		g.setColor(Color.GREEN);
		g.drawRect(0, 0, 119, 24);
	}
	//设置背景颜色
	private void setBackGround(Graphics g) {
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 120, 25);		
	}
}


 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值