工具类总结(5)-图片验证码工具类

来源:互联网 发布:淘宝卖家手机发货页面 编辑:程序博客网 时间:2024/05/17 13:11

struts验证码工具类及使用

import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;import java.awt.*;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.util.Random;public class ImageUtil {    public static byte[] getInstance(int width, int height, int num, String number) throws Exception {        byte[] codeArr = null;         /*         * 一,绘图         */        //step1,内存映像对象(画布)        BufferedImage image =                new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);        //step2,获得画笔        Graphics g = image.getGraphics();        //step3,给画笔设置颜色        Random r = new Random();        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));        //step4,给画布设置背景颜色        g.fillRect(0, 0, width, height);        //step5,重新给笔设置颜色        g.setColor(new Color(255, 255, 255));        g.setFont(new Font(null, Font.ITALIC, height - height / 5));        //step6,将验证码转换成图片        g.drawString(number, width / 10, height - height / 5);        //step7,加一些干扰线        for (int i = 0; i < 8; i++) {            g.setColor(new Color(r.nextInt(255),                    r.nextInt(255), r.nextInt(255)));            g.drawLine(r.nextInt(width), r.nextInt(height),                    r.nextInt(width), r.nextInt(height));        }        /*         * 二,压缩图片并输出         */        //1.字节数组输出流,向字节数组中输出信息        ByteArrayOutputStream baos = new ByteArrayOutputStream();        //2.压缩图片        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);        //图片中的二进制信息输出到内存中        encoder.encode(image);        codeArr = baos.toByteArray();        return codeArr;    }    //获取随机数    public static String getNumber(int num) {        String number = "";        String chars = "0123456789";        Random r = new Random();        for (int i = 0; i < num; i++) {            number += chars.charAt(                    r.nextInt(chars.length()));        }        return number;    }}

使用

action

import com.mlj.dangdang.util.ImageUtil;import com.mlj.dangdang.util.Struts2ScopeUtil;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.ServletActionContext;import javax.servlet.http.HttpServletResponse;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;public class ImgcodeAction extends ActionSupport {    private InputStream inputStream;    private String number;//验证码    private String checkImginfo;    public String getCheckImginfo() {        return checkImginfo;    }    public void setCheckImginfo(String checkImginfo) {        this.checkImginfo = checkImginfo;    }    public String getNumber() {        return number;    }    public void setNumber(String number) {        this.number = number;    }    public InputStream getInputStream() {        return inputStream;    }    public void setInputStream(InputStream inputStream) {        this.inputStream = inputStream;    }    /**     * 获取验证码     *     * @return     */    public String imgCode() {        String imgcode = ImageUtil.getNumber(4);        Struts2ScopeUtil.setSessionAttribute("imgCode", imgcode);//验证码        try {            byte[] attr = ImageUtil.getInstance(100, 30, 4, imgcode);            inputStream = new ByteArrayInputStream(attr);        } catch (Exception e) {            e.printStackTrace();        }        return "success";    }    /**     * 验证验证码     */    public void checkImg() {        HttpServletResponse response = ServletActionContext.getResponse();        response.setCharacterEncoding("UTF-8");        String myCode = Struts2ScopeUtil.getSessionAttribute("imgCode").toString();        if (myCode.equals(number)) {            try {                response.getWriter().print("1");//验证码正确            } catch (IOException e) {                e.printStackTrace();            }        } else {            try {                response.getWriter().print("0");//验证码错误            } catch (IOException e) {                e.printStackTrace();            }        }    }}

struts2.xml

<?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 name="struts.enable.DynamicMethodInvocation" value="true"/>    <package name="image" extends="struts-default" namespace="/image">        <action name="imgCode" method="imgCode" class="com.mlj.dangdang.action.ImgcodeAction">            <result name="success" type="stream">                <param name="inputName">inputStream</param>            </result>        </action>        <action name="checkImg" class="com.mlj.dangdang.action.ImgcodeAction" method="checkImg">        </action>    </package></struts>
原创粉丝点击