生成和识别图片二维码

1、引入pom文件



    com.google.zxing
    core
    3.2.1


    com.google.zxing
    javase
    3.2.1
2、生成和读取二维码

/**
 * 生成二维码
 */
public class CreateQrCode {

    public static void main(String[] args) {
        int width = 300;
        int height = 300;
        String format = "png";
        String content = "www.baidu.com";
        //定义二维码的参数
        HashMap map = new HashMap();
        //设置编码
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置纠错等级
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 2);

        try {
            //生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
            Path file = new File("E:/pic/test.png").toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 读取二维码
 */
public class ReadQrCode {

    public static void main(String[] args) {
        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            File file = new File("E:/pic/test.png");
            BufferedImage image = ImageIO.read(file);
            //定义二维码参数
            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET,"utf-8");

            //获取读取二维码结果
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Result result = multiFormatReader.decode(binaryBitmap, hints);

            System.out.println("读取二维码: " + result.toString());
            System.out.println("二维码格式: " + result.getBarcodeFormat());
            System.out.println("二维码内容: " + result.getText());
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


jquery.qrcode.js

1、引入jquery.min.js、jquery.qrcode.min.js 
2、页面


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




二维码
<% 
    String path = request.getContextPath();
    String bathPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); 
    pageContext.setAttribute("path", path);
    pageContext.setAttribute("bathPath", bathPath);
%>




    生成的二维码: 



你可能感兴趣的:(工具类)