Web网站登录验证码实现案例

1、验证码生成类-测试用的

package com.verifyCode;

import org.apache.commons.lang.RandomStringUtils;

import javax.imageio.stream.FileImageOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * Created by Liuxd on 2018-09-07.
 */
public class GenerateCode {

    /**
     * 去除 l、o、I、O、0、1
     * 目的避免混淆
     */
    private static final char[] CHAR_ARRAY = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789".toCharArray();

    public static void main(String[] args) {
        String checkCode = RandomStringUtils.random(4, CHAR_ARRAY);

        ByteArrayOutputStream os = (ByteArrayOutputStream) ImageUtil.generator(102, 25, checkCode);
        byte[] bytes = os.toByteArray();

        byte2image(bytes, "D:/911.jpg");
    }

    public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            System.out.println("图片已生成,地址:" + path);
        } catch (Exception ex) {
            System.out.println("Exception: " + ex);
            ex.printStackTrace();
        }
    }
}

 图片生成工具类

package com.verifyCode;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * Created by Liuxd on 2018-09-07.
 */
public class ImageUtil {
    public ImageUtil() {
    }

    public static OutputStream generator(int width, int height, String checkCode) {
        BufferedImage image = new BufferedImage(width, height, 5);
        Graphics g = image.getGraphics();
        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setColor(getRandColor(0, 255));
        g.drawRect(0, 0, width - 1, height - 1);
        g.setColor(getRandColor(160, 200));

        int i;
        int y;
        for (i = 0; i < 8; ++i) {
            i = random.nextInt(width);
            y = random.nextInt(height);
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            g.drawLine(i, y, x1, y1);
        }

        g.setColor(getRandColor(160, 200));

        for (i = 0; i < 100; ++i) {
            i = random.nextInt(width);
            y = random.nextInt(height);
            g.drawLine(i, y, i, y);
        }

        Font font = new Font("Arial Black", 2, 25);
        g.setFont(font);
        g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));

        for (i = 0; i < checkCode.length(); ++i) {
            g.drawString(String.valueOf(checkCode.charAt(i)), 22 * i + 2, 20);
        }

        g.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, "jpeg", os);
        } catch (IOException var11) {
            var11.printStackTrace();
        }

        return os;
    }

    private static Color getRandColor(int lower, int upper) {
        Random random = new Random();
        if (upper > 255) {
            upper = 255;
        }

        if (upper < 1) {
            upper = 1;
        }

        if (lower < 1) {
            lower = 1;
        }

        if (lower > 255) {
            lower = 255;
        }

        int r = lower + random.nextInt(upper - lower);
        int g = lower + random.nextInt(upper - lower);
        int b = lower + random.nextInt(upper - lower);
        return new Color(r, g, b);
    }
}

2、controller类

package com.sinosig.web.controller;

import com.kou.util.ImageUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


@Controller
@RequestMapping("/image")
public class ImageController {

	/**
	 * 去除 l、o、I、O、0、1
	 */
	private static final char[] CHAR_ARRAY = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789".toCharArray();

	/**
	 * @param session
	 * @return
	 */
	@RequestMapping("/generator")
	public ResponseEntity generator(HttpSession session){

		String checkCode = RandomStringUtils.random(4, CHAR_ARRAY);

		//TODO 直接返回byte数据
		ByteArrayOutputStream os = (ByteArrayOutputStream) ImageUtil.generator(102, 25, checkCode);
		byte[] bytes = os.toByteArray();
		try {
			os.close();
		} catch (IOException e) {
		}
		session.setAttribute("checkCode", checkCode);
		
		HttpHeaders responseHeaders = initHttpHeader();
		
		return new ResponseEntity(bytes,
                responseHeaders, HttpStatus.OK);
	}
	
	private HttpHeaders initHttpHeader() {
	    HttpHeaders responseHeaders = new HttpHeaders();
	    responseHeaders.setContentType(MediaType.IMAGE_JPEG);
	    responseHeaders.setCacheControl("no-cache");
	    responseHeaders.setPragma("No-cache");
	    responseHeaders.setDate("Expires", 0);
	    return responseHeaders;
	}
	
}

3、H5/Jsp页面验证码展示的代码实现

 

4、效果展示

Web网站登录验证码实现案例_第1张图片

你可能感兴趣的:(图片处理,解决方案)