图形验码器

如图

package com.oracle;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/random")
public class RandomImg extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		//设置给浏览器响应的类型
		resp.setContentType("image/png");
		ServletOutputStream os = resp.getOutputStream();
		
		//一个缓存区
		BufferedImage image=new BufferedImage(120, 40, BufferedImage.TYPE_INT_RGB);
		Graphics gs = image.getGraphics();
		gs.setColor(new Color(230,230,230));
		gs.fillRect(0, 0, 120, 40);
		
		
		//随机画50条线
		Random random=new Random();
		for(int i=0;i<50;i++)
		{
			gs.setColor(new Color(200+random.nextInt(30),100+random.nextInt(30),200+random.nextInt(30)));
			gs.drawLine(random.nextInt(120),random.nextInt(40), random.nextInt(120), random.nextInt(40));
		}
		
		//循环写出4个随机字母,并将它们存在stringBuilder,并且写在session上
		StringBuilder sBuffer=new StringBuilder();
		for(int i=0;i<4;i++)
		{
			String string=this.randChar();
			sBuffer.append(string);
			
			gs.setColor(new Color(160+random.nextInt(30),80+random.nextInt(30),80+random.nextInt(30)));
			gs.setFont(new Font("微软雅黑", Font.BOLD, 26));
			gs.drawString(string,16+i*30, 23+random.nextInt(5));
		}
		//必须用tostring
		//不然就是这个java.lang.StringBuilder cannot be cast to java.lang.String
		req.getSession().setAttribute("rand", sBuffer.toString());
		
		//将图片写到输出流
		ImageIO.write(image, "png", os);
		
	}
	//生成一个随机字母
public String randChar() {
	int re=(int) ((Math.random()*26)+65);
	return String.valueOf((char)re);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>