美文网首页
java生成二维码

java生成二维码

作者: 爱的旋转体 | 来源:发表于2020-01-16 17:59 被阅读0次

    1.pom文件添加maven依赖:

            <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
            <dependency>
                <groupId>com.google.zxing</groupId>
                <artifactId>core</artifactId>
                <version>3.4.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
            <dependency>
                <groupId>com.google.zxing</groupId>
                <artifactId>javase</artifactId>
                <version>3.4.0</version>
            </dependency>
    

    2.生成二维码工具类:

    package com.xzp.utils;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.util.Hashtable;
    
    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.lhtc.jv.config.Constants;
    
    public class QrCodeUtil {
        
        private static final String FORMAT_NAME = "jpg";
        // 二维码尺寸
        private static final int QRCODE_SIZE = 300;
    
        public static InputStream creatImage(String content) throws Exception {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, Constants.DEFAULT_URL_ENCODING);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                    hints);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, FORMAT_NAME, out);
            return new ByteArrayInputStream(out.toByteArray());
        }
        
    }
    

    相关文章

      网友评论

          本文标题:java生成二维码

          本文链接:https://www.haomeiwen.com/subject/qtfqzctx.html