Java生成带log的二维码

生成二维码案例

1.引入依赖


    com.google.zxing
    core
    3.3.3



    com.google.zxing
    javase
    3.3.3

2.生成二维码工具包

/**
 * 二维码工具
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868  qq-> 1948831260
 * @Date: 2020/11/16 22:38
 **/
public class QRCodeUtil {
    private static final Logger log= LoggerFactory.getLogger(QRCodeUtil.class);

    //CODE_WIDTH:二维码宽度,单位像素
    private static final int CODE_WIDTH = 400;
    //CODE_HEIGHT:二维码高度,单位像素
    private static final int CODE_HEIGHT = 400;
    //FRONT_COLOR:二维码前景色,0x000000 表示黑色
    private static final int FRONT_COLOR = 0x000000;
    //BACKGROUND_COLOR:二维码背景色,0xFFFFFF 表示白色
    //演示用 16 进制表示,和前端页面 CSS 的取色是一样的,注意前后景颜色应该对比明显,如常见的黑白
    private static final int BACKGROUND_COLOR = 0xFFFFFF;

    public static void createCodeToFile(String content, File codeImgFileSaveDir, String fileName) {
        try {
            if (StringUtils.isBlank(content) || StringUtils.isBlank(fileName)) {
                return;
            }
            content = content.trim();
            if (codeImgFileSaveDir==null || codeImgFileSaveDir.isFile()) {
                //二维码图片存在目录为空,默认放在桌面...
                codeImgFileSaveDir = FileSystemView.getFileSystemView().getHomeDirectory();
            }
            if (!codeImgFileSaveDir.exists()) {
                //二维码图片存在目录不存在,开始创建...
                codeImgFileSaveDir.mkdirs();
            }

            //核心代码-生成二维码
            BufferedImage bufferedImage = getBufferedImage(content);

            File codeImgFile = new File(codeImgFileSaveDir, fileName);
            ImageIO.write(bufferedImage, "png", codeImgFile);

            log.info("二维码图片生成成功:" + codeImgFile.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码并输出到输出流, 通常用于输出到网页上进行显示,输出到网页与输出到磁盘上的文件中,区别在于最后一句 ImageIO.write
     * write(RenderedImage im,String formatName,File output):写到文件中
     * write(RenderedImage im,String formatName,OutputStream output):输出到输出流中
     * @param content  :二维码内容
     * @param outputStream :输出流,比如 HttpServletResponse 的 getOutputStream
     */
    public static void createCodeToOutputStream(String content, OutputStream outputStream) {
        try {
            if (StringUtils.isBlank(content)) {
                return;
            }
            content = content.trim();
            //核心代码-生成二维码
            BufferedImage bufferedImage = getBufferedImage(content);

            //图片路径
            addQrCodeLogo(bufferedImage,new File("E://shFiles//QRCode//20231213151849.png"));

            //区别就是这一句,输出到输出流中,如果第三个参数是 File,则输出到文件中
            ImageIO.write(bufferedImage, "png", outputStream);

            log.info("二维码图片生成到输出流成功...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //核心代码-生成二维码
    private static BufferedImage getBufferedImage(String content) throws WriterException {

        //com.google.zxing.EncodeHintType:编码提示类型,枚举类型
        Map<EncodeHintType, Object> hints = new HashMap();

        //EncodeHintType.CHARACTER_SET:设置字符编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        //EncodeHintType.ERROR_CORRECTION:设置误差校正
        //ErrorCorrectionLevel:误差校正等级,L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
        //不设置时,默认为 L 等级,等级不一样,生成的图案不同,但扫描的结果是一样的
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

        //EncodeHintType.MARGIN:设置二维码边距,单位像素,值越小,二维码距离四周越近
        hints.put(EncodeHintType.MARGIN, 1);

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
        BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
        for (int x = 0; x < CODE_WIDTH; x++) {
            for (int y = 0; y < CODE_HEIGHT; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }
        return bufferedImage;
    }

    /**
     * 二维码下载方法
     * @param url
     * @param fileName
     * @param request
     * @param response
     */
    public static void downFile(String url, String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            //1.定义ContentType为("multipart/form-data")让浏览器自己解析文件格式
            response.setContentType("multipart/form-data");
            //2.中文名转码
            //response.setHeader("Content-disposition", "attachment; filename=\""+encodeChineseDownloadFileName(request, fileName+".xlsx") +"\"");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            //获得文件
            File file = new File(url+fileName);
            FileInputStream in = new FileInputStream(file);
            //3.将文件写入缓冲区OutputStream(out)
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            int b = 0;
            byte[] buffer = new byte[2048];
            while ((b=in.read(buffer)) != -1){
                //4.将缓冲区文件输出到客户端(out)
                out.write(buffer,0,b);
            }
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 给二维码添加logo
     * @Date 2023/09/24 22:33
     * @Param [bufferedImage, logoFile]
     * @return java.awt.image.BufferedImage
     */
    public static BufferedImage addQrCodeLogo(BufferedImage bufferedImage, File logoFile) throws IOException {
        Graphics2D graphics = bufferedImage.createGraphics();
        int matrixWidth = bufferedImage.getWidth();
        int matrixHeigh = bufferedImage.getHeight();

        // 读取logo图片文件
        BufferedImage logo = ImageIO.read(logoFile);
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        //  计算logo放置位置
        int x = bufferedImage.getWidth()  / 5*2;
        int y = bufferedImage.getHeight() / 5*2;
        int width = matrixWidth / 5;
        int height = matrixHeigh / 5;

        // 开始绘制图片
        graphics.drawImage(logo, x, y, width, height, null);
        graphics.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
        graphics.setStroke(new BasicStroke(5.0F, 1, 1));
        graphics.setColor(Color.white);
        graphics.drawRect(x, y, logoWidth, logoHeight);

        graphics.dispose();
        bufferedImage.flush();
        return bufferedImage;
    }


}
3.Controller 中调用生成二维码工具包
@RestController
@RequestMapping("/qrCode")
public class QrCodeController {

    private static final String RootPath="H:\\shFiles\\QRCode";
    private static final String FileFormat=".png";

    private static final ThreadLocal<SimpleDateFormat> LOCALDATEFORMAT=ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss"));

    //生成二维码并将其存放于本地目录
    @PostMapping("generate/file")
    public AjaxResult generateV1(String content){

        try {
            final String fileName=LOCALDATEFORMAT.get().format(new Date());
            File file = null;
            QRCodeUtil.createCodeToFile(content,file,fileName+FileFormat);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    //生成二维码并将其返回给前端调用者
    @PostMapping("generate/img")
    public AjaxResult generateV2(String content,HttpServletResponse servletResponse){

        try {
            QRCodeUtil.createCodeToOutputStream(content,servletResponse.getOutputStream());
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
       return AjaxResult.success();
    }


}
4.在postman测试

Java生成带log的二维码_第1张图片

你可能感兴趣的:(java,开发语言)