java生成图片验证码的源码

13 篇文章 0 订阅
8 篇文章 0 订阅
package com.sjl.common;


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


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


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class ImageServlet extends HttpServlet {
	String[] random = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
			"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
			"Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
			"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
			"y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };


	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int width = 130;
		int height = 50;
		// 设置响应格式
		response.setContentType("image/jpeg");
		// 获得输出流
		OutputStream os = response.getOutputStream();
		// 创建图片内存对象 给定长,宽 和格式
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 创建画笔
		Graphics g = image.createGraphics();
		Random ran = new Random();
		// 先给画笔设置颜色
		g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
				.nextInt(256)));
		// 画矩形
		g.fillRect(0, 0, width, height);
		// 设置字体 Font(String name,int style,int size)指定名称、样式和磅值大小
		Font font = new Font("宋体", Font.BOLD, 36);
		g.setFont(font);
		//最终生成验证码信息
		StringBuffer sb = new StringBuffer();
		//定义验证码位置
		int[] wid = {15,45,75,105};
		int[] hei = {35,40,30,28};
		// 绘制四位验证码
		for(int i=0;i<wid.length;i++){
			String str = random[ran.nextInt(62)];
			sb.append(str);
			g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
					.nextInt(256)));
			g.drawString(str, wid[i], hei[i]);
		}


		//将验证码发在session中
		request.getSession().setAttribute("chkCode", sb.toString());


		// 绘制干扰线
		for (int i = 0; i < 6; i++) {
			g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
					.nextInt(256)));
			g.drawLine(ran.nextInt(width), ran.nextInt(height), ran
					.nextInt(width), ran.nextInt(height));
		}


		// 将位图转为jpeg 格式传输
		// 使用JPEGImageEncoder 可以一边转换一边输出 把输出流传入
		JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(os);


		// 把BufferedImage对象中的图像信息编码后
		// 向创建该对象(encoder)时指定的输出流输出
		encode.encode(image);


	}


	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}


}


在SpringMVC中的写法:

package com.sjl.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@Controller
@RequestMapping("/image")
public class ImageController {
	
	String[] random = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
			"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
			"Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
			"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
			"y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

	
	@RequestMapping("/chkcode")
	public void chkcodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int width = 130;
		int height = 50;
		// 设置响应格式
		response.setContentType("image/jpeg");
		// 获得输出流
		OutputStream os = response.getOutputStream();
		// 创建图片内存对象 给定长,宽 和格式
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 创建画笔
		Graphics g = image.createGraphics();
		Random ran = new Random();
		// 先给画笔设置颜色
		g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
				.nextInt(256)));
		// 画矩形
		g.fillRect(0, 0, width, height);
		// 设置字体 Font(String name,int style,int size)指定名称、样式和磅值大小
		Font font = new Font("宋体", Font.BOLD, 36);
		g.setFont(font);
		//最终生成验证码信息
		StringBuffer sb = new StringBuffer();
		//定义验证码位置
		int[] wid = {15,45,75,105};
		int[] hei = {35,40,30,28};
		// 绘制四位验证码
		for(int i=0;i<wid.length;i++){
			String str = random[ran.nextInt(62)];
			sb.append(str);
			g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
					.nextInt(256)));
			g.drawString(str, wid[i], hei[i]);
		}

		//将验证码发在session中
		request.getSession().setAttribute("chkCode", sb.toString());

		// 绘制干扰线
		for (int i = 0; i < 6; i++) {
			g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
					.nextInt(256)));
			g.drawLine(ran.nextInt(width), ran.nextInt(height), ran
					.nextInt(width), ran.nextInt(height));
		}

		// 将位图转为jpeg 格式传输
		// 使用JPEGImageEncoder 可以一边转换一边输出 把输出流传入
		JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(os);

		// 把BufferedImage对象中的图像信息编码后
		// 向创建该对象(encoder)时指定的输出流输出
		encode.encode(image);
	}
	@RequestMapping("/downloadImage.jpeg")
	public void downloadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int width = 130;
		int height = 50;
		// 设置响应格式
		response.setContentType("application/octet-stream");
		// 获得输出流
		OutputStream os = response.getOutputStream();
		// 创建图片内存对象 给定长,宽 和格式
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 创建画笔
		Graphics g = image.createGraphics();
		Random ran = new Random();
		// 先给画笔设置颜色
		g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
				.nextInt(256)));
		// 画矩形
		g.fillRect(0, 0, width, height);
		// 设置字体 Font(String name,int style,int size)指定名称、样式和磅值大小
		Font font = new Font("宋体", Font.BOLD, 36);
		g.setFont(font);
		//最终生成验证码信息
		StringBuffer sb = new StringBuffer();
		//定义验证码位置
		int[] wid = {15,45,75,105};
		int[] hei = {35,40,30,28};
		// 绘制四位验证码
		for(int i=0;i<wid.length;i++){
			String str = random[ran.nextInt(62)];
			sb.append(str);
			g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
					.nextInt(256)));
			g.drawString(str, wid[i], hei[i]);
		}

		//将验证码发在session中
		request.getSession().setAttribute("chkCode", sb.toString());

		// 绘制干扰线
		for (int i = 0; i < 6; i++) {
			g.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
					.nextInt(256)));
			g.drawLine(ran.nextInt(width), ran.nextInt(height), ran
					.nextInt(width), ran.nextInt(height));
		}

		// 将位图转为jpeg 格式传输
		// 使用JPEGImageEncoder 可以一边转换一边输出 把输出流传入
		JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(os);

		// 把BufferedImage对象中的图像信息编码后
		// 向创建该对象(encoder)时指定的输出流输出
		encode.encode(image);
	}

}


假定该servlet 的 对应url 为  image/chkcode, 那么前台的HTML代码如下:

HTML代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'chkcodeImage.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="js/jquery.js"></script>
  </head>
  
  <body>
    <img id="chkcode" src="image/chkcode" οnclick="reload()"/>
    <a href="image/chkcode">显示原图</a>
    <a href="image/downloadImage.jpeg">下载图像</a>
    
    
  </body>
  
  
  <script type="text/javascript">
  	function reload() {
  		
  		$("#chkcode").attr("src", "image/chkcode/?q="+Math.random()); 
  		//$("#chkcode").attr("src", "image/chkcode");
  	}
  
  </script>
</html>

注:  reload 方法的使用, 通过更改src的值, 就可以实现点击图片的时候让图片重新加载实现图片刷新效果。但要注意的是, 在图片地址src不变的情况下让浏览器重新加载图片的话, 浏览器直接就去读取缓存了, 所以需要在地址后面通过加上"?querystring"的方式使得浏览器不读缓存,重新发起请求加载图片;这里的querystring可以随便写。



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值