1. 程式人生 > >生成二維碼(java後端)

生成二維碼(java後端)

需要引入2個jar包:

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

生成方法如下:

package com.payplatform.util;

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

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
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;

public class QRCodeUtil {
	//二維碼顏色  
    private static final int BLACK = 0xFF000000;  
    //二維碼顏色  
    private static final int WHITE = 0xFFFFFFFF;  
  
    public static void main(String[] args) throws Exception {
		zxingCodeCreate("http://www.baidu.com", 300, 300, "D:/qrcode.jpg", "jpg");
//    	zxingCodeAnalyze("D:/qrcode.jpg");
	}
    /** 
     * 生成二維碼
     * @param text    二維碼內容
     * @param width    二維碼寬 
     * @param height    二維碼高 
     * @param outPutPath    二維碼生成儲存路徑 
     * @param imageType     二維碼生成格式 
     */  
    public static void zxingCodeCreate(String text, int width, int height, String outPutPath, String imageType){  
        Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();  
        //設定編碼字符集  
        his.put(EncodeHintType.CHARACTER_SET, "utf-8");  
        try {  
            //1、生成二維碼  
            BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);  
              
            //2、獲取二維碼寬高  
            int codeWidth = encode.getWidth();  
            int codeHeight = encode.getHeight();  
              
            //3、將二維碼放入緩衝流  
            BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);  
            for (int i = 0; i < codeWidth; i++) {  
                for (int j = 0; j < codeHeight; j++) {  
                    //4、迴圈將二維碼內容定入圖片  
                    image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);  
                }  
            }  
            File outPutImage = new File(outPutPath);  
            //如果圖片不存在建立圖片  
            if(!outPutImage.exists())  
                outPutImage.createNewFile();  
            //5、將二維碼寫入圖片  
            ImageIO.write(image, imageType, outPutImage);  
        } catch (WriterException e) {  
            e.printStackTrace();  
            System.out.println("二維碼生成失敗");  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("生成二維碼圖片失敗");  
        }  
    }  
      
    /** 
     * 二維碼解析 
     * @param analyzePath    二維碼路徑 
     * @return 
     * @throws IOException 
     */  
    @SuppressWarnings({ "rawtypes", "unchecked" })  
    public static String zxingCodeAnalyze(String analyzePath) throws Exception{  
        MultiFormatReader formatReader = new MultiFormatReader();  
        String resultStr = null;  
        try {  
            File file = new File(analyzePath);  
            if (!file.exists())  
            {  
                return "二維碼不存在";  
            }  
            BufferedImage image = ImageIO.read(file);  
            LuminanceSource source = new BufferedImageLuminanceSource(image);  
            Binarizer binarizer = new HybridBinarizer(source);    
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);  
            Map hints = new HashMap();  
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
            Result result = formatReader.decode(binaryBitmap, hints); 
            resultStr = result.getText();
        } catch (NotFoundException e) {  
            e.printStackTrace();  
        }    
        System.out.println(resultStr);
        return resultStr;  
    }  
      

}