天天看點

Java實作二維碼制作

二維碼概述

二維碼又稱QR Code,QR全稱Quick Response,是用某種特定的幾何圖形按一定規律在平面(二維方向上)分布的黑白相間的圖形記錄資料符号資訊的。

zxing

1、引入pom檔案

<!-- zxing -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.2.1</version>
</dependency>
           

2、生成和讀取二維碼

/**
 * 生成二維碼
 */
public class CreateQrCode {

    public static void main(String[] args) {
        int width = ;
        int height = ;
        String format = "png";
        String content = "www.shuai.com";
        //定義二維碼的參數
        HashMap map = new HashMap();
        //設定編碼
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //設定糾錯等級
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, );

        try {
            //生成二維碼
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
            Path file = new File("E:/develop/qrcode.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:/develop/qrcode.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();
        }
    }
}
           

qrcodejar

1、引入qrcode的jar

2、生成二維碼,解析二維碼

/**
 * 二維碼圖檔
 */
public class MyQrCodeImage implements QRCodeImage{
    BufferedImage bufferedImage;

    public MyQrCodeImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;
    }

    public int getHeight() {
        return bufferedImage.getHeight();
    }

    public int getPixel(int arg0, int arg1) {
        return bufferedImage.getRGB(arg0, arg1);
    }

    public int getWidth() {
        return bufferedImage.getWidth();
    }

}

/**
 * 生成二維碼
 */
public class CreateQrCode {

    public static void main(String[] args) throws IOException {
        Qrcode x = new Qrcode();
        x.setQrcodeErrorCorrect('M');//設定糾錯等級
        x.setQrcodeEncodeMode('B');//N代表數字,A代表a-Z,B代表其它字元
        x.setQrcodeVersion();//設定版本
        String qrData = "www.shuai.com";
        int width =  +  * ( - );
        int height =  +  * ( - );
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gs = bufferedImage.createGraphics();
        //設定畫筆
        gs.setBackground(Color.WHITE);
        gs.setColor(Color.BLACK);
        gs.clearRect(, , width, height);

        int pixoff = ;//偏移量

        byte[] d = qrData.getBytes("gbk");
        if (d.length >  && d.length < ) {
            boolean[][] s = x.calQrcode(d);
            for (int i = ; i < s.length; i++) {
                for (int j = ; j < s.length; j++) {
                    if (s[j][i]) {
                        //往畫闆中填充内容
                        gs.fillRect(j*+pixoff,i*+pixoff,,);
                    }
                }
            }
        }
        gs.dispose();
        bufferedImage.flush();
        ImageIO.write(bufferedImage, "png", new File("E:/develop/code.png"));
    }
}

/**
 * 讀取二維碼
 */
public class ReadQrCode {

    public static void main(String[] args) throws IOException {
        File file = new File("E:/develop/code.png");
        BufferedImage bufferedImage = ImageIO.read(file);
        Qrcode qrcode = new Qrcode();
        QRCodeDecoder codeDecoder = new QRCodeDecoder();
        String result = new String(codeDecoder.decode(new MyQrCodeImage(bufferedImage)),"GBK");
        System.out.println(result);
    }
}
           

jquery.qrcode.js

1、引入jquery.min.js、jquery.qrcode.min.js

2、頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>二維碼</title>
<% 
    String path = request.getContextPath();
    String bathPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); 
    pageContext.setAttribute("path", path);
    pageContext.setAttribute("bathPath", bathPath);
%>
<script type="text/javascript" src="${path }/js/jquery.min.js"></script>
<script type="text/javascript" src="${path }/js/jquery.qrcode.min.js"></script>
</head>
<body>
    生成的二維碼: <br/>
    <div id="qrcode"></div>
    <script type="text/javascript">
        $('#qrcode').qrcode("www.shuai.cn");
    </script>
</body>

</html>