Java--生成二维码(2)

1.jsp生成二维码:
借助第三方的jar包,入zxing.jar和qrcode.jar
2.javaScript 比如:jquery.qrcode.js
在这次的讲解中我们使用的是maven工程项目,首先我们在pom.xml文件中引入两个依赖

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

2.创建一个CreateQRCode 类代码如下:

package com.unitop.Contorller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;

/**
 * 生成二维码的类
 */
public class CreateQRCode {

    public static void main(String[] args) {
        int width =300;//定义二维码的宽度
        int height = 300;//定义二维码的高度
        String fromat ="png";//二维码图片保存格式
        String cotent ="敏姐喊你抢小龙虾了";//二维码内容

        //定义二维码参数
        HashMap hints =new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");//设置编码格式
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);//设置纠错等级
        hints.put(EncodeHintType.MARGIN,2);//设置空白边框

        ///编写二维码的生成
        try {
            BitMatrix bitMatrix =  new MultiFormatWriter().encode(cotent, BarcodeFormat.QR_CODE,width,height,hints);
            Path path = new File("D:/img.png").toPath();//生成的二维码保存的路径和二维码的名字
            MatrixToImageWriter.writeToPath(bitMatrix,fromat,path);//s生成二维码
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

到这一步我们完成了二维码的生成。

猜你喜欢

转载自blog.csdn.net/weixin_37546725/article/details/81212115
今日推荐