BufferedImage圖片驗證碼

package com.servlet02.servlet;

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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 獲取隨機驗證碼圖像
 * 
 * @author Administrator
 *
 */
@WebServlet(value = "/getCodes02")
public class CodesServelt02 extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
		// 1.創建驗證碼圖像(寬,高,類型)
		BufferedImage image = new BufferedImage(160, 50, BufferedImage.TYPE_3BYTE_BGR);
		// 2.在該圖像上獲取畫筆
		Graphics g = image.getGraphics();
		// 設置圖像背景色和前景色
		g.setColor(Color.WHITE);//設置筆刷白色
		g.fillRect(1,1,158,48);//填充整個屏幕 (x,y,w,h)
		g.setColor(Color.BLACK); //設置筆刷 
		// 字體
		Font font = new Font("華文琥珀", Font.ITALIC , 24);
		g.setFont(font);
		// x軸座標
		int x = 20;
		for (int i = 1; i <= 6; i++) {
			// 3.獲取驗證碼
			String code = getCode();
			// 4.利用畫筆向圖像中寫隨機驗證碼(驗證碼,x軸,y軸)
			g.drawString(code, x, 30);
			x += 20;
		}
		// 5.釋放畫筆資源
		g.dispose();
		// 6. 將圖像輸出給客戶端
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	/**
	 * 獲取隨機驗證碼
	 * 
	 * @return
	 */
	protected String getCode() {
		// 要返回的隨機驗證碼(一位)
		String code = "";
		// 驗證碼庫
		String codes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		// 驗證碼庫的長度
		int len = codes.length();
		// 獲取隨機對象
		Random random = new Random();
		// 隨機驗證碼
		// 獲取隨機索引
		int index = random.nextInt(len);
		// 根據索引獲取隨機字符
		char ch = codes.charAt(index);
		code = String.valueOf(ch);
		return code;
	}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>codes.jsp</title>
</head>
<body>
	<img alt="" src="http://localhost:8080/Servlet02/getCodes02">
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章