java生成二維碼

本頁所用的jar包
其它例子:Zxing和QR CODE 生成與解析二維碼實例(帶logo篇)
生成QRCode式二維碼,三種方式(ZXing,QRcode,jQueryQRCode)

ZXing


先亮結果

這裏寫圖片描述

ZXing生成二維碼(可用微信掃一掃)

package com.wang.demo;

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

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.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 生成二維碼
 * @author wangxy
 *
 * @see  [相關類/方法]
 * @since  [產品/模塊版本]
 */
public class CreateQRCode {

    public static void main(String[] args) {

        int width = 300;
        int height = 300;
        String format = "png";
        String content = "你咋不上天呢?";
        String urlcontent = "http://www.baidu.com";//鏈接的寫法

        //定義二維碼參數
        Map hints = new HashMap();
//      hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//文字編碼 
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//容錯級別
        hints.put(EncodeHintType.MARGIN, 2);//圖片邊距

        //生成二維碼
        try {
            content = new String(content.getBytes("UTF-8"), "ISO-8859-1");//微信,UC可識別的編碼格式
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
            Path file = new File("D:/code/img.png").toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}

ZXing解析二維碼

package com.wang.demo;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

/**
 * 解析二維碼
 * @author wangxy
 *
 * @see  [相關類/方法]
 * @since  [產品/模塊版本]
 */
public class ReadQRCode {

    public static void main(String[] args) {
        MultiFormatReader formatReader = new MultiFormatReader();

        try {
            File file = new File("D:/code/img.png");

            BufferedImage image = ImageIO.read(file);

            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
                    new BufferedImageLuminanceSource(image)));

            // 定義二維碼參數
            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 文字編碼

            Result result;

            result = formatReader.decode(binaryBitmap, hints);

            System.out.println("解析結果:" + result.toString());
            System.out.println("二維碼格式類型:" + result.getBarcodeFormat());
            System.out.println("二維碼文本內容:" + result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}

QRCode

亮結果

這裏寫圖片描述

生成

package com.wang.demo;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

/**
 * http://www.swetake.com/qrcode/index-e.html 
 * https://osdn.jp/projects/qrcode/
 *
 * @author wangxy
 *
 * @see [相關類/方法]
 * @since [產品/模塊版本]
 */
public class CreateQRCode {

    public static void main(String[] args) throws IOException {
        Qrcode qrcode = new Qrcode();
        qrcode.setQrcodeErrorCorrect('M');// 糾錯等級(H L M Q)
        qrcode.setQrcodeEncodeMode('B');// N:數字 A:a-Z B:其它字符
        qrcode.setQrcodeVersion(7);// 版本 至49
        String qrData = "小樣,你咋不上天啊!";
        int width = 67 + 12 * (7 - 1);// 公式 67+12*(版本號-1)
        int height = 67 + 12 * (7 - 1);

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

        // 定義畫板
        Graphics2D gs = bufferedImage.createGraphics();
        gs.setBackground(Color.WHITE);
        gs.setColor(Color.BLACK);
        gs.clearRect(0, 0, width, height);

        int pixoff = 2;// 偏移量

        // 要繪製的內容
        byte[] d = qrData.getBytes("gb2312");

        if (d.length > 0 && d.length < 120) {
            boolean[][] s = qrcode.calQrcode(d);

            for (int i = 0; i < s.length; i++) {
                for (int j = 0; j < s.length; j++) {
                    if (s[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        }

        gs.dispose();
        bufferedImage.flush();

        ImageIO.write(bufferedImage, "png", new File("D:/code/qrcode.png"));
    }
}

編譯

package com.wang.demo;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

/**
 * http://www.swetake.com/qrcode/index-e.html 
 * https://osdn.jp/projects/qrcode/
 *
 * @author wangxy
 *
 * @see [相關類/方法]
 * @since [產品/模塊版本]
 */
public class ReadQRCode {

    public static void main(String[] args) throws DecodingFailedException, IOException {
        File file = new File("D:/code/qrcode.png");

        BufferedImage bufferedImage = ImageIO.read(file);

        QRCodeDecoder codeDecoder = new QRCodeDecoder();

        String result = new String(codeDecoder.decode(new MyQRCodeImage(bufferedImage)), "gb2312");

        System.out.println(result);
    }

}

實現接口

package com.wang.demo;

import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

public class MyQRCodeImage implements QRCodeImage{

    BufferedImage bufferedImage;

    public MyQRCodeImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;
    }
    @Override
    public int getHeight() {
        return bufferedImage.getHeight();
    }

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

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

}

jspQRCode

亮結果

這裏寫圖片描述

qrcode.jsp

<%@ 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>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.qrcode.min.js"></script>
</head>
<body>
生成的二維碼:<br>
<div id="qrcode"></div>

<script type="text/javascript">
    jQuery('#qrcode').qrcode("www.baidu.com");
/*  jQuery('#qrcode').qrcode({width: 64,height: 64,text: "小樣兒,你還真飛啊!"}); */
</script>
<a href="https://github.com/jeromeetienne/jquery-qrcode">網站</a>

</body>
</html>
發佈了86 篇原創文章 · 獲贊 83 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章