2012-05-14 53 views
8

Tengo un archivo jpeg que tiene código de barras 2D. La resolución de la imagen es 1593X1212. Estoy usando la biblioteca xing para decodificar este código de barras de la imagen. Obtuve el siguiente código en la red.La excepción com.google.zxing.NotFoundException se produce cuando se ejecuta el programa core java?

import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import javax.imageio.ImageIO; 
import com.google.zxing.BinaryBitmap; 
import com.google.zxing.ChecksumException; 
import com.google.zxing.FormatException; 
import com.google.zxing.LuminanceSource; 
import com.google.zxing.MultiFormatReader; 
import com.google.zxing.NotFoundException; 
    import com.google.zxing.Reader; 
import com.google.zxing.Result; 
import com.google.zxing.client.j2se.BufferedImageLuminanceSource; 
import com.google.zxing.common.HybridBinarizer; 


public class NewLibTest { 
    public static void main(String args[]){ 
    System.out.println(decode(new File("E:\\xyz.jpg"))); 
    } 

    /** 
     * Decode method used to read image or barcode itself, and recognize the barcode, 
     * get the encoded contents and returns it. 
    * @param <DecodeHintType> 
     * @param file image that need to be read. 
     * @param config configuration used when reading the barcode. 
     * @return decoded results from barcode. 
     */ 
    public static String decode(File file){//, Map<DecodeHintType, Object> hints) throws Exception { 
     // check the required parameters 
     if (file == null || file.getName().trim().isEmpty()) 
      throw new IllegalArgumentException("File not found, or invalid file name."); 
     BufferedImage image = null; 
     try { 
      image = ImageIO.read(file); 
     } catch (IOException ioe) { 
      try { 
       throw new Exception(ioe.getMessage()); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     if (image == null) 
      throw new IllegalArgumentException("Could not decode image."); 
     LuminanceSource source = new BufferedImageLuminanceSource(image); 
     BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); 
     MultiFormatReader barcodeReader = new MultiFormatReader(); 
     Result result; 
     String finalResult = null; 
     try { 
      //if (hints != null && ! hints.isEmpty()) 
       // result = barcodeReader.decode(bitmap, hints); 
      //else 
       result = barcodeReader.decode(bitmap); 
      // setting results. 
      finalResult = String.valueOf(result.getText()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      // throw new BarcodeEngine().new BarcodeEngineException(e.getMessage()); 
     } 
     return finalResult; 
    } 

}

Cuando ejecuta este sencillo programa básico de Java I dada excepción

com.google.zxing.NotFoundException 

Su ni siquiera le da a cualquier stackstrace.

Quiero preguntarles a los expertos por qué se produce ese tipo de excepción. ¡Gracias!

+2

¿Usted se ha solución de este problema? Estoy frente a problem..please misma que me haga saber –

Respuesta

3

Esa excepción se produce cuando no hay código de barras se encuentra en la imagen:

http://zxing.org/w/docs/javadoc/com/google/zxing/NotFoundException.html

+1

Gracias En respuesta Sir! Pero la imagen proporcionada arriba contiene un Código de Barras 2D, la resolución del código de barras es de aproximadamente 84Pix X 82pix. Entonces, ¿por qué el código anterior no encuentra el código de barras en la imagen? –

+0

¿Ha intentado utilizar el mismo código pero con una imagen de código de barras diferente? ¿Hay alguna imagen de muestra de código de barras para probar tu código? –

+0

Sí, he cambiado la imagen y he vuelto a ejecutar el programa, pero ha estado dando la misma excepción –

2

es normal; simplemente significa que no se encontró ningún código de barras. No ha proporcionado la imagen, por lo que no puedo decir si su imagen es incluso legible, y mucho menos tiene un formato de código de barras compatible.

+0

¿Cómo se puede "ajustar" con la precisión/configuración de búsqueda? ¿Hay documentación sobre eso? Cuando tengo un PNG grande (de un PDF) que tiene un código qr en la esquina superior izquierda, y todo lo demás está en blanco, no puede encontrarlo ... – mmcrae

6

Tuve el mismo problema. Utilicé una imagen que sabía que tenía un código QR válido y también obtuve la com.google.zxing.NotFoundException.

El problema es que la imagen que utiliza como fuente es demasiado grande para que la biblioteca decodifique. Después de que reduje el tamaño de mi imagen, funcionaba el decodificador de código QR.

A los fines de mi aplicación, el código QR de la imagen siempre estaría más o menos en la misma área, así que utilicé la función getSubimage de la clase BufferedImage para aislar el código QR.

 BufferedImage image; 
    image = ImageIO.read(imageFile); 
    BufferedImage cropedImage = image.getSubimage(0, 0, 914, 400); 
    // using the cropedImage instead of image 
    LuminanceSource source = new BufferedImageLuminanceSource(cropedImage); 
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); 
    // barcode decoding 
    QRCodeReader reader = new QRCodeReader(); 
    Result result = null; 
    try 
    { 
     result = reader.decode(bitmap); 
    } 
    catch (ReaderException e) 
    { 
     return "reader error"; 
    } 
0
try { 
       String a = textField_1.getText(); //my image path 
       InputStream barCodeInputStream = new FileInputStream(""+a); 
       BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream); 

       LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); 
       BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); 
       MultiFormatReader reader = new MultiFormatReader(); 
       com.google.zxing.Result result = reader.decode(bitmap); 

       System.out.println("Barcode text is " + result.getText()); 
       textField.setText(""+result.getText()); 
      } catch (Exception e) { 
       // TODO: handle exception 
       JOptionPane.showMessageDialog(null, "This image does not contain barcode", "Warning", JOptionPane.WARNING_MESSAGE); 
       e.printStackTrace(); 
      } 
0

he tenido el mismo problema, yo estaba llamando a un readQRCode (rutaArchivo, juego de caracteres, hintMap); y estaba recibiendo el mismo mensaje. Estaba llamando a una biblioteca que había escrito usando las bibliotecas zxing. Para solucionarlo, simplemente agregue los archivos jar (zxing) a su código de nivel superior, incluso si no se accede a las bibliotecas allí.

+0

sugiriendo volver a verificar los JAR en su classpath es no es probable que ayude a alguien que busca este error específico. No es realmente relevante para este tema – mmcrae

3

Tuve el mismo problema. Cuando estaba ejecutando casi exactamente el mismo código en las bibliotecas Java SE, funcionó. Cuando ejecuto el código de Android usando la misma imagen, no funcionó. Pasar muchas horas tratando de averiguar ...

  1. problema: tienes que cambiar el tamaño de la imagen para ser más pequeño. No puede usar directamente una imagen de teléfono inteligente. Es muy grande. En mi prueba, funcionó con una imagen de aproximadamente 200 KB.

Puede escalar un mapa de bits utilizando

Bitmap resize = Bitmap.createScaledBitmap(srcBitmap, dstWidth,dstHeight,false);

  1. problema: Usted tiene que encender algunas banderas. Jugar con casi todas las banderas esta solución funcionó para mí:

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

    ...

    MultiFormatReader mfr = null; 
    mfr = new MultiFormatReader(); 
    result = mfr.decode(binaryBitmap, tmpHintsMap); 
    
  2. problema: La biblioteca de Android ZXing ejecutar el código de barras escaneado una vez, suponiendo que el código de barras en la imagen ya tiene la orientación correcta. Si este no es el caso, debe ejecutarlo cuatro veces, ¡cada vez que gira la imagen alrededor de 90 grados!

Para la rotación puede utilizar este método. Ángulo es el ángulo en grados.

public Bitmap rotateBitmap(Bitmap source, float angle) 
    { 
      Matrix matrix = new Matrix(); 
      matrix.postRotate(angle); 
      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); 
    } 
0

Ya este código si se utiliza,

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, tmpHintsMap); 

    return qrCodeResult.getText(); 
} 

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, tmpHintsMap); 

    return qrCodeResult.getText(); 
} 

Para realizar cambios de este código. su trabajo conformly,

public static String readQRCode(String filePath, String charset, Map hintMap) 
throws FileNotFoundException, IOException, NotFoundException { 
    Map < DecodeHintType, Object > tmpHintsMap = new EnumMap < DecodeHintType, Object > (
     DecodeHintType.class); 

    //tmpHintsMap.put(DecodeHintType.TRY_HARDER, Boolean.FALSE); 
    //tmpHintsMap.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class)); 
    tmpHintsMap.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); 

    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
     new BufferedImageLuminanceSource(
      ImageIO.read(new FileInputStream(filePath))))); 

    Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, tmpHintsMap); 

    return qrCodeResult.getText(); 
} 
Cuestiones relacionadas