/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.biaopu.base.controller;
import com.biaopu.core.common.response.R;
import com.biaopu.core.constants.SecurityConstants;
import com.biaopu.core.service.SysUserService;
import com.biaopu.core.utils.Assert;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
/**
* @author lengleng
* @date 2017/12/18
* 验证码提供
*/
@Controller
public class ValidateCodeController {
@Autowired
private Producer producer;
@Autowired
private SysUserService userService;
/**
* 创建验证码
*
* @param request request
* @throws Exception
*/
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{randomStr}")
@ResponseBody //不加这个 无法映射,postman和前端会报404,但是可以正常访问
public R createCode(@PathVariable String randomStr, HttpServletRequest request) throws Exception {
Assert.isBlank(randomStr, "机器码不能为空");
//生成文字验证码
String text = producer.createText();
//生成图片验证码
BufferedImage image = producer.createImage(text);
userService.saveImageCode(randomStr, text);
//imgage 转成base64
ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
ImageIO.write(image, "png", baos);//写入流中
byte[] bytes = baos.toByteArray();//转换成字节
BASE64Encoder encoder = new BASE64Encoder();
String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
//ImageIO.write(bufferedImage, "png", new File("D:/qrcode1.png"));
System.out.println("值为:"+"data:image/jpg;base64,"+png_base64);
HashMap<String, Object> map = new HashMap<>();
map.put("image", png_base64);
return new R(map);
}
}
图文验证码,BufferedImage转base64图片
最新推荐文章于 2023-11-08 10:40:32 发布