QRCode 二維碼生成

package QRCode;

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

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.swetake.util.Qrcode;

public class QRCodeUtil {
    // 二維碼顏色
    private static final int BLACK = 0xFF000000;
    // 二維碼顏色
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * <span style="font-size:18px;font-weight:blod;">ZXing 方式生成二維碼</span>
     * 
     * @param text
     *            <a href="javascript:void();">二維碼內容</a>
     * @param width
     *            二維碼寬
     * @param height
     *            二維碼高
     * @param outPutPath
     *            二維碼生成保存路徑
     * @param imageType
     *            二維碼生成格式
     */
    public static void zxingCodeCreate(String text, int width, int height,
            String outPutPath, String imageType) {

        try {
            // 一、生成二維碼
            BitMatrix encode = new MultiFormatWriter().encode(
                    new String(text.getBytes("GBK"), "ISO-8859-1"),
                    BarcodeFormat.QR_CODE, width, height);

            // 二、獲取二維碼寬高
            int codeWidth = encode.getWidth();
            int codeHeight = encode.getHeight();

            // 三、將二維碼放入緩衝流
            BufferedImage image = new BufferedImage(codeWidth, codeHeight,
                    BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < codeWidth; i++) {
                for (int j = 0; j < codeHeight; j++) {
                    // 四、循環將二維碼內容定入圖片
                    image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
                }
            }
            File outPutImage = new File(outPutPath);
            // 若是圖片不存在建立圖片
            if (!outPutImage.exists())
                outPutImage.createNewFile();
            // 五、將二維碼寫入圖片
            ImageIO.write(image, imageType, outPutImage);
            System.out.println("OK");
        } catch (WriterException e) {
            e.printStackTrace();
            System.out.println("二維碼生成失敗");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("生成二維碼圖片失敗");
        }
    }

    /**
     * <span style="font-size:18px;font-weight:blod;">二維碼解析</span>
     * 
     * @param analyzePath
     *            二維碼路徑
     * @return
     * @throws IOException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Result zxingCodeAnalyze(String analyzePath) throws Exception {
        MultiFormatReader formatReader = new MultiFormatReader();
        Result result = null;
        try {
            File file = new File(analyzePath);
            if (!file.exists()) {
                return null;
            }
            BufferedImage image = ImageIO.read(file);

            LuminanceSource source = new LuminanceSourceUtil(image);
            // LuminanceSource source = new BufferedImageLuminanceSource(image);

            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Hashtable hints = new Hashtable();
            hints.put(DecodeHintType.CHARACTER_SET, "gb2312");
            result = formatReader.decode(binaryBitmap, hints);
            String resultStr = result.getText();
            System.out.println("解碼內容:" + resultStr);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * <span style="font-size:18px;font-weight:blod;">QRCode 方式生成二維碼</span>
     * 
     * @param content
     *            二維碼內容
     * @param imgPath
     *            二維碼生成路徑
     * @param version
     *            二維碼版本
     * @param isFlag
     *            是否生成Logo圖片 爲NULL不生成
     */
    public static void QRCodeCreate(String content, String imgPath,
            int version, String logoPath) {

        try {
            Qrcode qrcodeHandler = new Qrcode();
            // 設置二維碼排錯率,可選L(7%) M(15%) Q(25%) H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小
            qrcodeHandler.setQrcodeErrorCorrect('M');
            // N表明數字,A表明字符a-Z,B表明其餘字符
            qrcodeHandler.setQrcodeEncodeMode('B');
            // 版本1爲21*21矩陣,版本每增1,二維碼的兩個邊長都增4;因此版本7爲45*45的矩陣;最高版本爲是40,是177*177的矩陣
            qrcodeHandler.setQrcodeVersion(version);
            // 根據版本計算尺寸
            int imgSize = 67 + 12 * (version - 1);
            byte[] contentBytes = content.getBytes("gb2312");
            BufferedImage bufImg = new BufferedImage(imgSize, imgSize,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D gs = bufImg.createGraphics();
            gs.setBackground(Color.WHITE);
            gs.clearRect(0, 0, imgSize, imgSize);
            // 設定圖像顏色 > BLACK
            gs.setColor(Color.BLACK);
            // 設置偏移量 不設置可能致使解析出錯
            int pixoff = 2;
            // 輸出內容 > 二維碼
            if (contentBytes.length > 0 && contentBytes.length < 130) {
                boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
                for (int i = 0; i < codeOut.length; i++) {
                    for (int j = 0; j < codeOut.length; j++) {
                        if (codeOut[j][i]) {
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            } else {
                System.err.println("QRCode content bytes length = "
                        + contentBytes.length + " not in [ 0,130 ]. ");
            }
            // 判斷是否須要添加logo圖片
            if (logoPath != null) {
                File icon = new File(logoPath);
                if (icon.exists()) {
                    int width_4 = imgSize / 4;
                    int width_8 = width_4 / 2;
                    int height_4 = imgSize / 4;
                    int height_8 = height_4 / 2;
                    Image img = ImageIO.read(icon);
                    gs.drawImage(img, width_4 + width_8, height_4 + height_8,
                            width_4, height_4, null);
                    gs.dispose();
                    bufImg.flush();
                } else {
                    System.out.println("Error: login圖片不存在!");
                }
            }
            gs.dispose();
            bufImg.flush();
            // 建立二維碼文件
            File imgFile = new File(imgPath);
            if (!imgFile.exists())
                imgFile.createNewFile();
            // 根據生成圖片獲取圖片
            String imgType = imgPath.substring(imgPath.lastIndexOf(".") + 1,
                    imgPath.length());
            // 生成二維碼QRCode圖片
            ImageIO.write(bufImg, imgType, imgFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

引用jar分享包地址:https://pan.baidu.com/s/14A4PiAvuFqvnQc3qarSxJwjavascript

相關文章
相關標籤/搜索