求java做验证码代码

pig_xj 2012-11-24 02:12:42
动态的验证码 代码 或资料
...全文
427 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
bigdata-sb 2014-01-11
  • 打赏
  • 举报
回复
引用 3 楼 sgyyz 的回复:

这位哥们的代码我仔细看了一下,生成验证码的部分代码很不过,但是你的类设计有点问题
,你看你的这两行代码

VerifyCodeImage image = new VerifyCodeImage();
image = image.createCheckCode();

createCheckCode()方法本来就是返回VerifyCodeImage类型的,但是我要调用这个方法我还必须要先创建一个VerifyCodeImage对象出来,这一下就搞了两个对象出来了。。。
我修改了一下,做成了再struts2框架中能够使用的。。你可以看一下

package util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import javax.imageio.ImageIO;

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

/**
* CheckCode.java
*
* @author King<br/>
*
* @Description 验证码生成类
* @since 1.0.0
* @Date 2012-2-29下午1:50:25
*/
public class VerifyCodeImage {



/**
* 创建对象的时候就调用createCheckCode方法
*/
public VerifyCodeImage() {
createCheckCode();
}

private int width = 102;
private int height = 28;
private int codeCount = 4;



private Random random = new Random();

/**
* 验证码图片
*/
private BufferedImage buffImg;
/**
* 验证码字符串
*/
private String checkCodeStr;

public BufferedImage getBuffImg() {
return buffImg;
}

public void setBuffImg(BufferedImage buffImg) {
this.buffImg = buffImg;
}

public String getCheckCodeStr() {
return checkCodeStr;
}

public void setCheckCodeStr(String checkCodeStr) {
this.checkCodeStr = checkCodeStr;
}

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public int getCodeCount() {
return codeCount;
}

public void setCodeCount(int codeCount) {
this.codeCount = codeCount;
}

// /**
// *
// * @Description:创建验证码对象
// * @since 1.0.0
// * @Date:2012-3-1 上午10:26:20
// * @return CheckCode
// */
// public VerifyCodeImage createCheckCode() {
// VerifyCodeImage checkCode = new VerifyCodeImage();
// checkCode.setCheckCodeStr(createRandomCode());
// checkCode.setBuffImg(disturb());
// return checkCode;
// }
/**
*
* @Description:创建验证码对象
* @since 1.0.0
* @Date:2012-3-1 上午10:26:20
* 不能返回任何值
*/
public void createCheckCode() {
this.setCheckCodeStr(createRandomCode());
this.setBuffImg(disturb());
}

/**
*
* @Description:随机产生的验证码
* @since 1.0.0
* @Date:2012-3-1 上午10:20:05
* @return String
*/
private String createRandomCode() {
StringBuffer randomCode = new StringBuffer();

String strRand = null;
int xx = width / (codeCount + 1);
int codeY = height - 4;
char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };

Graphics2D graphics = graphicsInit();
graphics.setColor(createColor());

for (int i = 0; i < codeCount; i++) {
strRand = String.valueOf(codeSequence[random.nextInt(32)]);
randomCode.append(strRand);

graphics.drawString(strRand, (i + 1) * xx, codeY);
}
return randomCode.toString();
}

/**
*
* @Description:创建颜色
* @since 1.0.0
* @Date:2012-2-29 下午4:47:14
* @return Color
*/
private Color createColor() {
Color color[] = new Color[10];
color[0] = new Color(113, 31, 71);
color[1] = new Color(37, 0, 37);
color[2] = new Color(111, 33, 36);
color[3] = new Color(0, 0, 112);
color[4] = new Color(14, 51, 16);
color[5] = new Color(1, 1, 1);
color[6] = new Color(72, 14, 73);
color[7] = new Color(65, 67, 29);
color[8] = new Color(116, 86, 88);
color[9] = new Color(41, 75, 71);

return color[random.nextInt(10)];
}

/**
*
* @Description:绘制类初始化
* @since 1.0.0
* @Date:2012-3-1 上午10:17:52
* @return Graphics2D
*/
private Graphics2D graphicsInit() {
Graphics2D graphics = buffImgInit().createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.setFont(new Font("Fixedsys", Font.BOLD, height - 2));
graphics.drawRect(0, 0, width - 1, height - 1);
return graphics;
}

/**
*
* @Description:BufferedImage初始化
* @since 1.0.0
* @Date:2012-3-1 上午11:07:18
* @return BufferedImage
*/
private BufferedImage buffImgInit() {
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
return buffImg;
}

/**
*
* @Description:绘制干扰特性
* @since 1.0.0
* @Date:2012-3-1 上午11:45:32
* @return BufferedImage
*/
private BufferedImage disturb() {
drawDisturbLine(buffImg.createGraphics());
return twistImage();
}

/**
*
* @Description:画干扰线使图象中的认证码不易被其它程序探测到
* @since 1.0.0
* @Date:2012-2-29 下午4:28:23
* @param graphics
* void
*/
private void drawDisturbLine(Graphics2D graphics) {
graphics.setColor(Color.BLACK);
int x = 0;
int y = 0;
int xl = 0;
int yl = 0;
for (int i = 0; i < 15; i++) {
x = random.nextInt(width);
y = random.nextInt(height);
xl = random.nextInt(20);
yl = random.nextInt(10);
graphics.drawLine(x, y, x + xl, y + yl);
}
}

/**
*
* @Description:正弦曲线Wave扭曲图片
* @since 1.0.0
* @Date:2012-3-1 下午12:49:47
* @return BufferedImage
*/
private BufferedImage twistImage() {
double dMultValue = random.nextInt(7) + 3;// 波形的幅度倍数,越大扭曲的程序越高,一般为3
double dPhase = random.nextInt(6);// 波形的起始相位,取值区间(0-2*PI)

BufferedImage destBi = new BufferedImage(buffImg.getWidth(), buffImg
.getHeight(), BufferedImage.TYPE_INT_RGB);

for (int i = 0; i < destBi.getWidth(); i++) {
for (int j = 0; j < destBi.getHeight(); j++) {
int nOldX = getXPosition4Twist(dPhase, dMultValue, destBi
.getHeight(), i, j);
int nOldY = j;
if (nOldX >= 0 && nOldX < destBi.getWidth() && nOldY >= 0
&& nOldY < destBi.getHeight()) {
destBi.setRGB(nOldX, nOldY, buffImg.getRGB(i, j));
}
}
}
return destBi;
}

/**
*
* @Description:获取扭曲后的x轴位置
* @since 1.0.0
* @Date:2012-3-1 下午3:17:53
* @param dPhase
* @param dMultValue
* @param height
* @param xPosition
* @param yPosition
* @return int
*/
private int getXPosition4Twist(double dPhase, double dMultValue,
int height, int xPosition, int yPosition) {
double PI = 3.1415926535897932384626433832799; // 此值越大,扭曲程度越大
double dx = (double) (PI * yPosition) / height + dPhase;
double dy = Math.sin(dx);
return xPosition + (int) (dy * dMultValue);
}

/**
*
* @Description:将图像进行输出到文件
* @since 1.0.0
* @Date:2012-3-1 上午11:56:19
* @param pathName
* @return String
*/
public String createImgFile(String pathName) {
File file = new File(pathName);
if (file.isFile() && file.exists()) {
file.delete();
}
try {
ImageIO.write(buffImg, "jpeg", file);
} catch (IOException e) {
e.printStackTrace();
}
return pathName;
}

/**
* 我加上的方法,在struts2中,用stream类型的result来做的话就更方便了,
* 直接new VerifyCodeImage() 然后调用getStream方法就可以了
* @param image
* @return
* @throws Exception
*/
public InputStream getStream(BufferedImage image) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
byte[] imageBts = bos.toByteArray();
InputStream in = new ByteArrayInputStream(imageBts);
return in;
}



}


--------------action------------------
[code=java]
package action;

import java.io.InputStream;
import java.util.Map;

import util.VerifyCodeImage;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class VerifyCodeImageAction1 extends ActionSupport {

/**
*
*/
private static final long serialVersionUID = 1L;

private InputStream image;


public InputStream getImage() {
return image;
}

public void setImage(InputStream image) {
this.image = image;
}

@Override
public String execute() throws Exception {

VerifyCodeImage v = new VerifyCodeImage();


image = v.getStream(v.getBuffImg());

ActionContext context = ActionContext.getContext();
Map<String, Object> session = context.getSession();

session.put("checkCodeStr", v.getCheckCodeStr());
return super.execute();
}

}
[code=html]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.ui.theme" value="simple"></constant>
<constant name="struts.configuration.xml.reload" value="true"></constant>


<package name="generic" namespace="/generic" extends="json-default">

<global-results>
<result name="ajax" type="json">
<param name="root">result</param>
</result>
</global-results>

<action name="verifyCodeImage" class="action.VerifyCodeImageAction1">
<result type="stream">
<param name="inputName">image</param>
</result>
</action>
<action name="checkVerifyCodeImage" class="action.CheckVerifyCodeStrAction">
<result name="input" type="json">
<param name="root">result</param>
</result>
</action>
</package>

</struts>


sgyyz 2012-11-26
  • 打赏
  • 举报
回复
package org.bean.util;

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

import javax.imageio.ImageIO;


/**
 * CheckCode.java
 * 
 * @author King<br/>
 *         
 * @Description 验证码生成类
 * @since 1.0.0
 * @Date 2012-2-29下午1:50:25
 */
public class VerifyCodeImage {
	private int width = 102;
	private int height = 28;
	private int codeCount = 4;

	private Random random = new Random();

	/**
	 * 验证码图片
	 */
	private BufferedImage buffImg;
	/**
	 * 验证码字符串
	 */
	private String checkCodeStr;

	/**
	 * 
	 * @Description:创建验证码对象
	 * @since 1.0.0
	 * @Date:2012-3-1 上午10:26:20
	 * @return CheckCode
	 */
	public VerifyCodeImage createCheckCode() {
		VerifyCodeImage checkCode = new VerifyCodeImage();
		checkCode.setCheckCodeStr(createRandomCode());
		checkCode.setBuffImg(disturb());
		return checkCode;
	}

	/**
	 * 
	 * @Description:随机产生的验证码
	 * @since 1.0.0
	 * @Date:2012-3-1 上午10:20:05
	 * @return String
	 */
	private String createRandomCode() {
		StringBuffer randomCode = new StringBuffer();

		String strRand = null;
		int xx = width / (codeCount + 1);
		int codeY = height - 4;
		char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
				'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };

		Graphics2D graphics = graphicsInit();
		graphics.setColor(createColor());

		for (int i = 0; i < codeCount; i++) {
			strRand = String.valueOf(codeSequence[random.nextInt(32)]);
			randomCode.append(strRand);

			graphics.drawString(strRand, (i + 1) * xx, codeY);
		}
		return randomCode.toString();
	}

	/**
	 * 
	 * @Description:创建颜色
	 * @since 1.0.0
	 * @Date:2012-2-29 下午4:47:14
	 * @return Color
	 */
	private Color createColor() {
		Color color[] = new Color[10];
		color[0] = new Color(113, 31, 71);
		color[1] = new Color(37, 0, 37);
		color[2] = new Color(111, 33, 36);
		color[3] = new Color(0, 0, 112);
		color[4] = new Color(14, 51, 16);
		color[5] = new Color(1, 1, 1);
		color[6] = new Color(72, 14, 73);
		color[7] = new Color(65, 67, 29);
		color[8] = new Color(116, 86, 88);
		color[9] = new Color(41, 75, 71);

		return color[random.nextInt(10)];
	}

	/**
	 * 
	 * @Description:绘制类初始化
	 * @since 1.0.0
	 * @Date:2012-3-1 上午10:17:52
	 * @return Graphics2D
	 */
	private Graphics2D graphicsInit() {
		Graphics2D graphics = buffImgInit().createGraphics();
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, width, height);
		graphics.setFont(new Font("Fixedsys", Font.BOLD, height - 2));
		graphics.drawRect(0, 0, width - 1, height - 1);
		return graphics;
	}

	/**
	 * 
	 * @Description:BufferedImage初始化
	 * @since 1.0.0
	 * @Date:2012-3-1 上午11:07:18
	 * @return BufferedImage
	 */
	private BufferedImage buffImgInit() {
		buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		return buffImg;
	}

	/**
	 * 
	 * @Description:绘制干扰特性
	 * @since 1.0.0
	 * @Date:2012-3-1 上午11:45:32
	 * @return BufferedImage
	 */
	private BufferedImage disturb() {
		drawDisturbLine(buffImg.createGraphics());
		return twistImage();
	}

	/**
	 * 
	 * @Description:画干扰线使图象中的认证码不易被其它程序探测到
	 * @since 1.0.0
	 * @Date:2012-2-29 下午4:28:23
	 * @param graphics
	 *            void
	 */
	private void drawDisturbLine(Graphics2D graphics) {
		graphics.setColor(Color.BLACK);
		int x = 0;
		int y = 0;
		int xl = 0;
		int yl = 0;
		for (int i = 0; i < 15; i++) {
			x = random.nextInt(width);
			y = random.nextInt(height);
			xl = random.nextInt(20);
			yl = random.nextInt(10);
			graphics.drawLine(x, y, x + xl, y + yl);
		}
	}

	/**
	 * 
	 * @Description:正弦曲线Wave扭曲图片
	 * @since 1.0.0
	 * @Date:2012-3-1 下午12:49:47
	 * @return BufferedImage
	 */
	private BufferedImage twistImage() {
		double dMultValue = random.nextInt(7) + 3;// 波形的幅度倍数,越大扭曲的程序越高,一般为3
		double dPhase = random.nextInt(6);// 波形的起始相位,取值区间(0-2*PI)

		BufferedImage destBi = new BufferedImage(buffImg.getWidth(),
				buffImg.getHeight(), BufferedImage.TYPE_INT_RGB);

		for (int i = 0; i < destBi.getWidth(); i++) {
			for (int j = 0; j < destBi.getHeight(); j++) {
				int nOldX = getXPosition4Twist(dPhase, dMultValue,
						destBi.getHeight(), i, j);
				int nOldY = j;
				if (nOldX >= 0 && nOldX < destBi.getWidth() && nOldY >= 0
						&& nOldY < destBi.getHeight()) {
					destBi.setRGB(nOldX, nOldY, buffImg.getRGB(i, j));
				}
			}
		}
		return destBi;
	}

	/**
	 * 
	 * @Description:获取扭曲后的x轴位置
	 * @since 1.0.0
	 * @Date:2012-3-1 下午3:17:53
	 * @param dPhase
	 * @param dMultValue
	 * @param height
	 * @param xPosition
	 * @param yPosition
	 * @return int
	 */
	private int getXPosition4Twist(double dPhase, double dMultValue,
			int height, int xPosition, int yPosition) {
		double PI = 3.1415926535897932384626433832799; // 此值越大,扭曲程度越大
		double dx = (double) (PI * yPosition) / height + dPhase;
		double dy = Math.sin(dx);
		return xPosition + (int) (dy * dMultValue);
	}

	/**
	 * 
	 * @Description:将图像进行输出到文件
	 * @since 1.0.0
	 * @Date:2012-3-1 上午11:56:19
	 * @param pathName
	 * @return String
	 */
	public String createImgFile(String pathName) {
		File file = new File(pathName);
		if (file.isFile() && file.exists()) {
			file.delete();
		}
		try {
			ImageIO.write(buffImg, "jpeg", file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return pathName;
	}

	public BufferedImage getBuffImg() {
		return buffImg;
	}

	public void setBuffImg(BufferedImage buffImg) {
		this.buffImg = buffImg;
	}

	public String getCheckCodeStr() {
		return checkCodeStr;
	}

	public void setCheckCodeStr(String checkCodeStr) {
		this.checkCodeStr = checkCodeStr;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getCodeCount() {
		return codeCount;
	}

	public void setCodeCount(int codeCount) {
		this.codeCount = codeCount;
	}

}
private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		VerifyCodeImage image = new VerifyCodeImage();
		image = image.createCheckCode();
		request.getSession().setAttribute("verifyCode", image.getCheckCodeStr());
		ImageIO.write(image.getBuffImg(), "jpg", response.getOutputStream());
	}
asdf544265772 2012-11-26
  • 打赏
  • 举报
回复
一个jsp页面就搞定了,看我空间 收藏的代码里有 希望对你有用
Inhibitory 2012-11-24
  • 打赏
  • 举报
回复

58,455

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧