如果给前端返回图片,以验证码为例

最近做项目,遇到给前端返回验证码。 第一次做的时候,直接以流的形式返回:

1.生成验证码的图片:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;
 
/**
 * 验证码生成器
 * 
 * @author
 */
public class VerificationCodeImgUtil {
	// 图片的宽度。
	private int width = 160;
	// 图片的高度。
	private int height = 40;
	// 验证码字符个数
	private int codeCount = 5;
	// 验证码干扰线数
	private int lineCount = 150;
	// 验证码
	private String code = null;
	// 验证码图片Buffer
	private BufferedImage buffImg = null;
 
	// 验证码范围,去掉0(数字)和O(拼音)容易混淆的(小写的1和L也可以去掉,大写不用了)
	private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
			'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
 
	/**
	 * 默认构造函数,设置默认参数
	 */
	public VerificationCodeImgUtil() {
		this.createCode();
	}
 
	/**
	 * @param width
	 *            图片宽
	 * @param height
	 *            图片高
	 */
	public VerificationCodeImgUtil(int width, int height) {
		this.width = width;
		this.height = height;
		this.createCode();
	}
 
	/**
	 * @param width
	 *            图片宽
	 * @param height
	 *            图片高
	 * @param codeCount
	 *            字符个数
	 * @param lineCount
	 *            干扰线条数
	 */
	public VerificationCodeImgUtil(int width, int height, int codeCount, int lineCount) {
		this.width = width;
		this.height = height;
		this.codeCount = codeCount;
		this.lineCount = lineCount;
		this.createCode();
	}
 
	public void createCode() {
		int x = 0, fontHeight = 0, codeY = 0;
		int red = 0, green = 0, blue = 0;
 
		x = width / (codeCount + 2);// 每个字符的宽度(左右各空出一个字符)
		fontHeight = height - 2;// 字体的高度
		codeY = height - 4;
 
		// 图像buffer
		buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffImg.createGraphics();
		// 生成随机数
		Random random = new Random();
		// 将图像填充为白色
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		// 创建字体,可以修改为其它的
		Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
		// Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, fontHeight);
		g.setFont(font);
 
		for (int i = 0; i < lineCount; i++) {
			// 设置随机开始和结束坐标
			int xs = random.nextInt(width);// x坐标开始
			int ys = random.nextInt(height);// y坐标开始
			int xe = xs + random.nextInt(width / 8);// x坐标结束
			int ye = ys + random.nextInt(height / 8);// y坐标结束
 
			// 产生随机的颜色值,让输出的每个干扰线的颜色值都将不同。
			red = random.nextInt(255);
			green = random.nextInt(255);
			blue = random.nextInt(255);
			g.setColor(new Color(red, green, blue));
			g.drawLine(xs, ys, xe, ye);
		}
 
		// randomCode记录随机产生的验证码
		StringBuffer randomCode = new StringBuffer();
		// 随机产生codeCount个字符的验证码。
		for (int i = 0; i < codeCount; i++) {
			String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
			// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
			red = random.nextInt(255);
			green = random.nextInt(255);
			blue = random.nextInt(255);
			g.setColor(new Color(red, green, blue));
			g.drawString(strRand, (i + 1) * x, codeY);
			// 将产生的四个随机数组合在一起。
			randomCode.append(strRand);
		}
		// 将四位数字的验证码保存到Session中。
		code = randomCode.toString();
	}
 
	public void write(String path) throws IOException {
		OutputStream sos = new FileOutputStream(path);
		this.write(sos);
	}
 
	public void write(OutputStream sos) throws IOException {
		ImageIO.write(buffImg, "png", sos);
		sos.close();
	}
 
	public BufferedImage getBuffImg() {
		return buffImg;
	}
 
	public String getCode() {
		return code;
	}
 
	/**
	 * 测试函数,默认生成到d盘
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		VerificationCodeImgUtil vCode = new VerificationCodeImgUtil(160, 40, 5, 150);
		try {
			String path = "D:/" + new Date().getTime() + ".png";
			System.out.println(vCode.getCode() + " >" + path);
			vCode.write(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2.调用接口返回验证码的流

 /** 
    * @Title: validateCode 
    * @Description: (响应验证码页面 ) 
    * @param @param request
    * @param @param response
    * @param @return
    * @param @throws Exception    设定文件 
    * @return String    返回类型 
    * @throws 
    */
    @RequestMapping(value="/validateCode")  
    public String validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{  
        // 设置响应的类型格式为图片格式  
        response.setContentType("image/jpeg");  
        //禁止图像缓存。  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
      
        HttpSession session = request.getSession();  
      
        VerificationCodeImgUtil vCode = new VerificationCodeImgUtil(120,40,5,100);  
        session.setAttribute("code", vCode.getCode());  
        vCode.write(response.getOutputStream());  
        return null;  
    } 

3.返回的输出流,因此,前端只需直接展示:

但是前端说,他们不想这么做,只想要加密的base64的字符串。因此我这边稍作修改:

修改后的完成代码:

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;  
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;  
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;  
import java.util.Random;  

/** 
 * 验证码生成器 
 * 
 * @author  
 */  
public class ImageValidateCode {  
    // 图片的宽度。  
    private int width = 160;  
    // 图片的高度。  
    private int height = 40;  
    // 验证码字符个数  
    private int codeCount = 5;  
    // 验证码干扰线数  
    private int lineCount = 150;  
    // 验证码  
    private String code = null;  
    // 验证码图片Buffer  
    private BufferedImage buffImg = null;  

    // 验证码范围,去掉0(数字)和O(拼音)容易混淆的(小写的1和L也可以去掉,大写不用了)  
    private char[] codeSequence = { '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', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',  
            'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9'};  

    /** 
     * 默认构造函数,设置默认参数 
     */  
    public ImageValidateCode() {  
        this.createCode();  
    }  

    /** 
     * @param width  图片宽 
     * @param height 图片高 
     */  
    public ImageValidateCode(int width, int height) {  
        this.width = width;  
        this.height = height;  
        this.createCode();  
    }  

    /** 
     * @param width     图片宽 
     * @param height    图片高 
     * @param codeCount 字符个数 
     * @param lineCount 干扰线条数 
     */  
    public ImageValidateCode(int width, int height, int codeCount, int lineCount) {  
        this.width = width;  
        this.height = height;  
        this.codeCount = codeCount;  
        this.lineCount = lineCount;  
        this.createCode();  
    }  

    public void createCode() {  
        int x = 0, fontHeight = 0, codeY = 0;  
        int red = 0, green = 0, blue = 0;  

        x = width / (codeCount + 2);//每个字符的宽度(左右各空出一个字符)  
        fontHeight = height - 2;//字体的高度  
        codeY = height - 4;  

        // 图像buffer  
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
        Graphics2D g = buffImg.createGraphics();  
        // 生成随机数  
        Random random = new Random();  
        // 将图像填充为白色  
        g.setColor(Color.WHITE);  
        g.fillRect(0, 0, width, height);  
        // 创建字体,可以修改为其它的  
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);  
//        Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, fontHeight);  
        g.setFont(font);  

        for (int i = 0; i < lineCount; i++) {  
            // 设置随机开始和结束坐标  
            int xs = random.nextInt(width);//x坐标开始  
            int ys = random.nextInt(height);//y坐标开始  
            int xe = xs + random.nextInt(width / 8);//x坐标结束  
            int ye = ys + random.nextInt(height / 8);//y坐标结束  

            // 产生随机的颜色值,让输出的每个干扰线的颜色值都将不同。  
            red = random.nextInt(255);  
            green = random.nextInt(255);  
            blue = random.nextInt(255);  
            g.setColor(new Color(red, green, blue));  
            g.drawLine(xs, ys, xe, ye);  
        }  

        // randomCode记录随机产生的验证码  
        StringBuffer randomCode = new StringBuffer();  
        // 随机产生codeCount个字符的验证码。  
        for (int i = 0; i < codeCount; i++) {  
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);  
            // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。  
            red = random.nextInt(255);  
            green = random.nextInt(255);  
            blue = random.nextInt(255);  
            g.setColor(new Color(red, green, blue));  
            g.drawString(strRand, (i + 1) * x, codeY);  
            // 将产生的四个随机数组合在一起。  
            randomCode.append(strRand);  
        }  
        // 将四位数字的验证码保存到Session中。  
        code = randomCode.toString();  
    }  

    public void write(String path) throws IOException {  
        OutputStream sos = new FileOutputStream(path);  
        this.write(sos);  
    }  

    public void write(OutputStream sos) throws IOException {  
        ImageIO.write(buffImg, "png", sos);  
        sos.close();  
    }  

    public BufferedImage getBuffImg() {  
        return buffImg;  
    }  

    public String getCode() {  
        return code;  
    }
    
	public  InputStream getImageStream(BufferedImage bimage) {
		InputStream is = null;
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		ImageOutputStream imOut;
		try {
			imOut = ImageIO.createImageOutputStream(bs);
			ImageIO.write(bimage, "png", imOut);
			is = new ByteArrayInputStream(bs.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
}  
	/** 
	 * 响应验证码页面 
	 * @return 
	 */  
	@GetMapping(value="/imageValidateCode")  
	public String validateCode() throws Exception{  
	    HttpSession session = request.getSession();  
	    ImageValidateCode vCode = new ImageValidateCode();  
	    session.setAttribute("code", vCode.getCode());  
	    InputStream io = vCode.getImageStream(vCode.getBuffImg());
	    byte [] data = new byte[io.available()];
	    io.read(data);
	    io.close();
	    // 加密
	    return new String(Base64.getEncoder().encode(data));
	}

验证:

	public static void main(String[] args) {
		byte [] bs = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAKAAAAAoCAIAAAD2TmbPAAAHxElEQ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qWqJaZo3G5TtXthC4wDAyuWV19di/R38MtuxfTTYC56kIeFvFzrvGIZZ6DBiW4wV3ereuzBy45B3DIMNzpw0dNFmTFTvbmdu9WgMMj570NsZAyAwv/OkDhiJMX9p8bkhkADANMZ9OAKM5cC0naSN2JKvwvUXWZ2zKLh71cICTEiIyvbbIfUNJulIvHXaHddrdy/YgQFjekwhaQg89eorbXlrXGvIubSHeIiqMmseRGJsKbHk+MyxIcnDLlqWO+BVjPGGEseGkLQde/w97SD4eMPYIRj3IVrxjqTiYAxptmYfBKvMX6VOh7nZoP4v/o95Sd8sjJEcjJE5kmEvd7BB2JP6PUaxMHNpH+dgLt3m6DFIGGZ8rBhLhi9gZZA0xFjlBp9zaUpU2AH2Xb1tox56VcEmcmSGpPe6iAn1NQmZg0lz5oQBe2Hr3lEZRzuM6gTPsanQ0fzarJd09/yvIeGZ53x+NyQS4BZDLxmjSE/4ah2k7iYfYPwvVlmhqWGJQG8AAAAASUVORK5CYII=");
		String path = "D:/" + new Date().getTime() + ".png";
		try {
			OutputStream oStream  = new FileOutputStream(path);
			oStream.write(bs);
			oStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

前端展示:略。

你可能感兴趣的:(验证码)