2013-09-18 4 views
11

Некоторые вопросы об использовании ZXing ...Чтение QRCode с ZXing в Java

Я пишу следующий код для чтения штрих-кода с изображения:

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.

enter image description here enter image description here

Он может работать на Code128, но не для QRCode. Любой знает почему ...

+1

Чтобы решить эту проблему, я, наконец, вырезал область, где штрих-код и QRCode находятся в моей программе. Тогда их можно признать. – Johnny

+0

как вы вырезали область/указали ее? Я в подобной ситуации. – mmcrae

+1

Уважаемый mmcrae, я сначала прочитал все изображение в буфер ----> BufferedImage tmpBfrImage = ImageIO.read (whatFile); затем используйте метод getSubimage ----> BufferedImage tmpBarCodeBfrImage = tmpBfrImage.getSubimage (whatBarCodeArea.x, whatBarCodeArea.y, whatBarCodeArea.width, whatBarCodeArea.height); – Johnny

ответ

0

Этот код работал для меня.

public static List<string> ScanForBarcodes(string path) 
{ 
    return ScanForBarcodes(new Bitmap(path)); 
} 

public static List<string> ScanForBarcodes(Bitmap bitmap) 
{ 
    // initialize a new Barcode reader. 
    BarcodeReader reader = new BarcodeReader 
    { 
    TryHarder = true, // TryHarder is slower but recognizes more Barcodes 
    PossibleFormats = new List<BarcodeFormat> // in the ZXing There is an Enum where all supported barcodeFormats were contained 
    { 
     BarcodeFormat.CODE_128, 
     BarcodeFormat.QR_CODE, 
     //BarcodeFormat. ... ; 
    } 
    }; 
    return reader.DecodeMultiple(bitmap).Select(result => result.Text).ToList(); // return only the barcode string. 
                       // If you want the full Result use: return reader.DecodeMultiple(bitmap); 
} 

this вы используете (ZXing.Net) Lib ли?

+0

Я использую его java-библиотеку. – Johnny

+0

Является ли ZXing.net сломанным? Это не работает для меня вообще. Метод Decode всегда возвращает null. – Zack

5

Просьба пройти через это link для полного учебника. Автором этого кода является Джо. Я еще не разработал этот код, поэтому я просто делаю Copy paste, чтобы убедиться, что это доступно в случае, если ссылка сломана.

Автор использует ZXing (Zebra Crossing Library), вы можете скачать его с here, для этого урока.

QR Code читать и писать программы в Java:

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(); 
    } 
} 

Maven зависимостей для библиотеки ZXing QR Code:

<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> 
+1

Хотя эта ссылка может ответить на вопрос, лучше включить здесь основные части ответа и предоставить ссылку для справки. Ответные ссылки могут стать недействительными, если связанная страница изменится. – Florent

+1

Спасибо за комментарий, я скоро его обновлю. –

+0

Загрузите связанные банки из http://www.java2s.com/Code/Jar/z/zxing.htm –

6

Любопытно ваш код работает для меня, но у меня было чтобы удалить подсказку.

tmpHintsMap.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);

Когда мой образ не является чистым штрих-кодов, этот намек сломал мой результат.

Спасибо!

+2

Правильно, вы не хотите устанавливать это ни на что.Это «правда», если оно имеет какую-либо ценность. Хм. Возможно, это не лучшая вещь. –

+0

странно, что это помешало бы ему найти не-штрих-коды, поскольку это то, – mmcrae

Смежные вопросы