栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

二维码和条形码生成

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二维码和条形码生成

二维码和条形码生成 前言

之前说了微信小程序生成微信小程序码,现在说一下普通的二维码的生成。

(这些都是亲测,都可以使用)

导入依赖(maven)
        
        
            com.google.zxing
            core
            3.4.1
        
        
            com.google.zxing
            javase
            3.4.1
        
自定义一个工具类
package com.miniapp.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;



@Slf4j
public class QrCodeUtil {

    

    private static final int WIDTH = 300;
    

    private static final int HEIGHT = 300;
    

    private static final String FORMAT = "png";
    

    private static final Map HINTS = new HashMap();

    static {
        // 字符编码
        HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
        HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二维码与图片边距
        HINTS.put(EncodeHintType.MARGIN, 2);
    }

    
    public static void generateBarCodeFile(String content, String paths) {

        Code128Writer writer = new Code128Writer();
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, HINTS);
        Path path = Paths.get(paths);
        if (!StrUtil.isEmpty(content)) {
            try {
                MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
            } catch (IOException e) {
                log.error("生成条形码失败:{}", e.getMessage());
            }
        }
    }


    
    public static OutputStream generateBarCodeStream(String content, HttpServletResponse response) {


        Code128Writer writer = new Code128Writer();
        OutputStream outputStream = null;
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, HINTS);
        if (!StrUtil.isEmpty(content)) {
            try {
                // 字节输出流
                outputStream = response.getOutputStream();
                MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
                return outputStream;
            } catch (IOException e) {
                log.error("生成条形码失败:{}", e.getMessage());
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        log.error("流关闭失败:{}", e.getMessage());
                    }
                }
            }
        }
        return null;
    }

    
    public static String generateBarCodeBase64(String content) {

        String base64;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Code128Writer writer = new Code128Writer();
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, HINTS);
        if (!StrUtil.isEmpty(content)) {
            try {
                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ImageIO.write(bufferedImage, FORMAT, os);
                base64 = Base64.encode(os.toByteArray());
                return base64;
            } catch (Exception e) {
                log.error("生成二维码失败:{}", e.getMessage());
            } finally {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error("流关闭失败:{}", e.getMessage());
                }

            }
        }
        return null;
    }


    
    public static void generateQrCodeFile(String content, String paths) {

        MultiFormatWriter writer = new MultiFormatWriter();
        if (!StrUtil.isEmpty(content)) {
            try {
                // 字节输出流
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
                Path path = Paths.get(paths);
                MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
            } catch (Exception e) {
                log.error("生成二维码失败:{}", e.getMessage());
            }
        }

    }


    
    public static OutputStream generateQrCodeStream(String content, HttpServletResponse response) {

        MultiFormatWriter writer = new MultiFormatWriter();
        OutputStream outputStream = null;
        if (!StrUtil.isEmpty(content)) {
            try {
                // 字节输出流
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
                outputStream = response.getOutputStream();
                MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
                return outputStream;
            } catch (Exception e) {
                log.error("生成二维码失败:{}", e.getMessage());
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        log.error("流关闭失败:{}", e.getMessage());
                    }
                }
            }
        }
        return null;
    }


    
    public static String generateQrCodeBase64(String content) {

        String base64;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        if (!StrUtil.isEmpty(content)) {
            try {
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ImageIO.write(bufferedImage, FORMAT, os);
                base64 = Base64.encode(os.toByteArray());
                return base64;
            } catch (Exception e) {
                log.error("生成二维码失败:{}", e.getMessage());
            } finally {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error("流关闭失败:{}", e.getMessage());
                }

            }
        }
        return null;
    }


}

这些分别生成条形码和二维码,包括生成本地的,base64的,和文件流的,按需求进行调用方法即可。

注意:生成文件流的需要传参HttpServletResponse 这一点需要注意

类似

    @GetMapping("getQrcode")
    public OutputStream getQrcode (HttpServletResponse response) throws IOException {
        
        OutputStream s = CodeUtil.generateQrCodeStream("测试文件流", response);
        return s;

    }
扩展

如果你想让你的二维码内容进行加密,你完全可以使用hutool包的加密工具类进行加密解密。

也可以选择对称加密和非对称加密,这是你自己进行取舍的。

package com.study.mybatisplus.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;


public class SecurityUtil {

    
    private static final String STR_KEY = "mybatis_plus_security_key";


    
    private static byte[] getKey() {
        byte[] byteKey = StrUtil.bytes(STR_KEY);
        return SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), byteKey).getEncoded();
    }


    
    public static String getEncryptStr(String content) {
        DES des = SecureUtil.des(SecurityUtil.getKey());
        return des.encryptHex(content);

    }


    
    public static String getDecryptStr(String encryptStr) {
        DES des = SecureUtil.des(SecurityUtil.getKey());
        return des.decryptStr(encryptStr);
    }
}

具体的细节就需要你自己慢慢进行取舍了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859578.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号