在Java中使用Zxing读取QRCode [英] Reading QRCode with Zxing in Java

查看:96
本文介绍了在Java中使用Zxing读取QRCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于使用Zxing的一些问题...

Some questions about using Zxing...

我编写以下代码以从图像中读取条形码:

I write the following code to read barcode from an image:

public class BarCodeDecode 
{
    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        try
        {
            String tmpImgFile = "D:\\FormCode128.TIF";

            Map<DecodeHintType,Object> tmpHintsMap = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
            tmpHintsMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            tmpHintsMap.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
            tmpHintsMap.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);

            File tmpFile = new File(tmpImgFile);
            String tmpRetString = BarCodeUtil.decode(tmpFile, tmpHintsMap);
            //String tmpRetString = BarCodeUtil.decode(tmpFile, null);
            System.out.println(tmpRetString);
        }
        catch (Exception tmpExpt)
        {
            System.out.println("main: " + "Excpt err! (" + tmpExpt.getMessage() + ")");
        }
        System.out.println("main: " + "Program end.");
    }

}

public class BarCodeUtil 
{
    private static BarcodeFormat DEFAULT_BARCODE_FORMAT = BarcodeFormat.CODE_128;

    /**
      * Decode method used to read image or barcode itself, and recognize the barcode,
      * get the encoded contents and returns it.
      * @param whatFile image that need to be read.
      * @param config configuration used when reading the barcode.
      * @return decoded results from barcode.
      */
     public static String decode(File whatFile, Map<DecodeHintType, Object> whatHints) throws Exception 
     {
         // check the required parameters
         if (whatFile == null || whatFile.getName().trim().isEmpty())
             throw new IllegalArgumentException("File not found, or invalid file name.");
         BufferedImage tmpBfrImage;
         try 
         {
             tmpBfrImage = ImageIO.read(whatFile);
         } 
         catch (IOException tmpIoe) 
         {
             throw new Exception(tmpIoe.getMessage());
         }
         if (tmpBfrImage == null)
             throw new IllegalArgumentException("Could not decode image.");
         LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
         BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
         MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
         Result tmpResult;
         String tmpFinalResult;
         try 
         {
             if (whatHints != null && ! whatHints.isEmpty())
                 tmpResult = tmpBarcodeReader.decode(tmpBitmap, whatHints);
             else
                 tmpResult = tmpBarcodeReader.decode(tmpBitmap);
             // setting results.
             tmpFinalResult = String.valueOf(tmpResult.getText());
         } 
         catch (Exception tmpExcpt) 
         {
             throw new Exception("BarCodeUtil.decode Excpt err - " + tmpExcpt.toString() + " - " + tmpExcpt.getMessage());
         }
         return tmpFinalResult;
    }
}

我尝试读取以下两个包含code128和QRCode的图像.

I try to read the following two images that contains code128 and QRCode.

它适用于code128,但不适用于QRCode.谁知道为什么...

It can work for the code128 but not for the QRCode. Any one knows why...

推荐答案

请仔细阅读以下链接以获取完整的教程.该代码的作者是Joe.我还没有开发此代码,所以我只是在进行复制粘贴,以确保在链接断开的情况下可用.

Please go through this link for complete Tutorial. The author of this code is Joe. I have not developed this code, so I am just doing Copy paste to make sure this is available in case link is broken.

作者正在使用ZXing(斑马线库),可以从此处下载,对于本教程.

The author is using ZXing(Zebra Crossing Library) you can download it from here, for this tutorial.

Java中的QR码读写程序:

package com.javapapers.java;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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.BinaryBitmap;
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;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCode {

  public static void main(String[] args) throws WriterException, IOException,
      NotFoundException {
    String qrCodeData = "Hello World!";
    String filePath = "QRCode.png";
    String charset = "UTF-8"; // or "ISO-8859-1"
    Map<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

    createQRCode(qrCodeData, filePath, charset, hintMap, 200, 200);
    System.out.println("QR Code image created successfully!");

    System.out.println("Data read from QR Code: "
        + readQRCode(filePath, charset, hintMap));

  }

  public static void createQRCode(String qrCodeData, String filePath,
      String charset, Map hintMap, int qrCodeheight, int qrCodewidth)
      throws WriterException, IOException {
    BitMatrix matrix = new MultiFormatWriter().encode(
        new String(qrCodeData.getBytes(charset), charset),
        BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);
    MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath
        .lastIndexOf('.') + 1), new File(filePath));
  }

  public static String readQRCode(String filePath, String charset, Map hintMap)
      throws FileNotFoundException, IOException, NotFoundException {
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
        new BufferedImageLuminanceSource(
            ImageIO.read(new FileInputStream(filePath)))));
    Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap,
        hintMap);
    return qrCodeResult.getText();
  }
}

ZXing QR Code库的Maven依赖项:

<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>2.2</version>
</dependency>

<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>2.2</version>
</dependency>

这篇关于在Java中使用Zxing读取QRCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆