python調用zxing項目進行二維碼

摘要:首先創建一個java的maven項目,加入zxing相關包,編寫二維碼相關代碼,調試運行,打包;然後創建一個python項目,安裝jpype,編寫代碼把相關的jar包加載,運行。

0. 創建一個maven項目

1. 配置pom.xml文件

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->          <dependency>              <groupId>com.google.zxing</groupId>              <artifactId>core</artifactId>              <version>3.3.0</version>          </dependency>            <dependency>              <groupId>com.google.zxing</groupId>              <artifactId>javase</artifactId>              <version>3.0.0</version>          </dependency>             <dependency>              <groupId>com.alibaba</groupId>              <artifactId>fastjson</artifactId>              <version>1.1.29</version>          </dependency> 

2. 生成與識別二維碼###

import java.io.File;  import java.io.IOException;  import java.nio.file.FileSystems;  import java.nio.file.Path;  import java.util.HashMap;  import java.util.Map;    import javax.imageio.ImageIO;    import com.alibaba.fastjson.JSONObject;  import com.google.zxing.BarcodeFormat;  import com.google.zxing.BinaryBitmap;  import com.google.zxing.DecodeHintType;  import com.google.zxing.EncodeHintType;  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.client.j2se.MatrixToImageWriter;  import com.google.zxing.common.BitMatrix;  import com.google.zxing.common.HybridBinarizer;    public class QRCode {        public static void main(String[] args) {          QRCode qrcode = new QRCode();          // 內容          JSONObject json = new JSONObject();          json.put("blog", "http://blog.csdn.net/ld326");          json.put("author", "happyprince");          String content = json.toJSONString();          // 生成二維碼          qrcode.EncodeQR("D:\info-qr.png", content, 200, 200, "png");          // 解釋二維碼          boolean b = qrcode.DecodeQR("D:\info-qr.png");          if (b) {              System.out.println("解釋出來是二維碼!!!");          }        }        /**       * 生成圖像       */      public void EncodeQR(String filePath, String content, int width,              int height, String format) {          Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();          hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");          try {              // 生成矩陣              BitMatrix bitMatrix = new MultiFormatWriter().encode(content,                      BarcodeFormat.QR_CODE, width, height, hints);              // 輸出圖像              Path path = FileSystems.getDefault().getPath(filePath);              System.out.println(path);              MatrixToImageWriter.writeToPath(bitMatrix, format, path);          } catch (WriterException e) {              // TODO Auto-generated catch block              e.printStackTrace();          } catch (IOException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }          System.out.println("生成二維碼成功.");      }        /**       * 解析圖像       */      public boolean DecodeQR(String filePath) {          boolean b = false;          try {              // 讀入圖片,轉化成位圖              BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(                      new BufferedImageLuminanceSource(ImageIO.read(new File(                              filePath)))));                // 設置額外的一些信息,例如讀取入來的提示信息              Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();              hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");                // 對圖像進行解碼              Result result = new MultiFormatReader().decode(binaryBitmap, hints);              // 打印信息              // sb.append("content:  " + result.getText() + " ");              // sb.append("format:  " + result.getBarcodeFormat() + " ");              b = true;          } catch (IOException e) {              // sb.append(e + " " + "filePath=" + filePath);              e.printStackTrace();            } catch (NotFoundException e) {              // sb.append(e + " " + "filePath=" + filePath);              e.printStackTrace();          }          return b;      }  }

3. 打包

生成qrcode包,命名為qrcode-1.0.0.jar;再把maven下載的兩個包(javase-3.0.0.jar,core-3.3.0.jar)與這個包放在一起,一會會把這些包加載到jvm中運行。

4. 安裝jpype

目前配置的是win7,下載地址:http://www.lfd.uci.edu/~gohlke/pythonlibs/#jpype

5. 創建python項目

編寫python代碼

# -*- coding: utf-8 -*-  import logging    from jpype import *    from common.globalVars import JAR_PATH    @singleton  class QRCode:      """          判斷圖片是否QR圖片      """        def __init__(self):          logging.info('starJVM..')          startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=%s;%s;%s" % (              JAR_PATH + 'core-3.3.0.jar',              JAR_PATH + 'javase-3.0.0.jar',              JAR_PATH + 'qrcode-1.0.0.jar'          ))          QRCode = JClass("com.lr.jpype.jpype.QRCode")          self.qr = QRCode()        def is_qrcode(self, file_name):          b = self.qr.DecodeQR(file_name)          return b      def __del__(self):          shutdownJVM()          logging.info('shutdownJVM..')  qrc = QRCode()  print(qrc.is_qrcode('d:/1.jpg'))

其中裝飾類,為了完成單例的功能

import logging  def singleton(cls):      instances = {}      def wrapper(*args, **kwargs):          if cls not in instances:              instances[cls] = cls(*args, **kwargs)          return instances[cls]      logging.info('singleton size %d' % (len(instances)))      return wrapper

總結,這個主要是python依靠jpype,jpype運行JVM,JVM調用相關的包處理QR,主要實現的包為google的zxing。