生成随机数字的图片验证码

第一步:

首先先写一个验证码图片生成类CreateAuthCode

package com.sunsheng.commons;

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

public class CreateAuthCode extends BufferedImage {

	private Graphics graphics;
	private int width;
	private int height;

	public CreateAuthCode(int width, int height, int imageType) {
		super(width, height, imageType);
		this.width = width;
		this.height = height;

		graphics = getGraphics();

		//设置图片的背景颜色
		setBgColor();
		
		//给图片设置一个边框
		setBorder();
		
		//往图片中写入字符串
		setText();
	}

	private void setBorder() {
		//设置边框的颜色
		graphics.setColor(Color.RED);
		
		//为了防止边框写到图片外面,所以处理一下
		graphics.drawRect(1, 1, width - 2, height - 2);

	}

	private void setBgColor() {

		graphics.setColor(Color.WHITE);
		
		//往矩形区域填充设置的颜色
		graphics.fillRect(0, 0, width, height);
	}

	private void setText() {

		graphics.setColor(Color.BLUE);
		
		//设置文件的字体
		graphics.setFont(new Font("宋体", Font.BOLD, 60));
		
		// graphics.drawString("中国", 10, 80);

		int x = 10;
		//往图片中写入4个随机的整数(0~9)
		for (int i = 0; i < 4; i++) {

			int num = new Random().nextInt(10);
			//坐标是字符串左下角的那个点
			graphics.drawString(String.valueOf(num), x, 65);
			
			//数字字符串是半角格式占30个像素,每个字符串之间距离10个像素,所以x轴要右移40像素
			x += 40;
		}
	}

}
第二步:

在Servlet中输入图片

package com.sunsheng;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sunsheng.commons.CreateAuthCode;

public class AuthCode extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//设置http响应头,告诉浏览器服务器发送的是一个jpeg格式的图片
		resp.setHeader("content-type", "image/jpeg");
		
		
		//在内存中创建一个图片
		//调用ImageIO工具的write方法把图片从内存写到Response的OutputStream中
		ImageIO.write(new CreateAuthCode(180, 80, BufferedImage.TYPE_INT_RGB)
						, "jpg"
						, resp.getOutputStream());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值