com.google.zxing.NotFoundException-識別圖片二維碼信息錯誤


一、問題由來

自己在做一個小程序項目的后台,其中需要使用到識別圖片二維碼信息,而且是必須在Java后台進行識別二維碼操作。去百度里面很快找到一個方法,

可以識別簡單的二維碼,而且自己生成的簡單的二維碼圖片也能夠正確識別,這樣我就以為可以了。項目中有個需求,將自己生成的二維碼圖片和其他

圖片合成一張新的圖片,功能我也很快實現,並且部署到阿里雲的測試服務器,生成二維碼圖片沒有任何問題。可是在進行聯合調試時,發現問題。報

了如標題中的錯誤,導致二維碼不能正確識別,程序不能正常運行。

二、問題分析

拿到這個問題后,感覺很奇怪以前都好好的,怎么突然就不行了呢?自己以前是親自測試過使用自己寫的程序來識別二維碼信息,100%確認是沒問題的。

把這個問題往百度里面一扔,很快出來很多的答案,自己也看了其中的幾篇博文,了解到報錯的原因。報錯的原因是,如果使用自己原來的識別圖片的方法

識別簡單的二維碼沒問題,比如識別的圖片只有單張圖片,不是合成、處理過的,如果是處理過的圖片,那么就會出現錯誤。

/**
* 解析二維碼圖片
* @param filePath 圖片路徑
*/
public static String decodeQR(String filePath) {
if (StringUtils.isBlank(filePath)) {
return "-1";
}
String content = "";
HashMap<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); // 指定編碼方式,防止中文亂碼
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
try (FileInputStream fis = new FileInputStream(filePath)){
BufferedImage image = ImageIO.read(fis);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
MultiFormatReader reader = new MultiFormatReader();
Result result = reader.decode(binaryBitmap, hints);
content = result.getText();
} catch (Exception e) {
e.printStackTrace();
log.error("解析圖片二維碼異常--->" + e.getMessage());
return "-1";
}
return content;
}

三、解決方案

知道問題的原因后,自己嘗試找去找解決辦法,在百度里面查看了很多的答案,基本上都一個一個的嘗試,最終都沒有解決。

https://www.cnblogs.com/rencongums/articles/5805176.html


https://www.cnblogs.com/liyanli-mu640065/p/9165584.html


https://www.shangmayuan.com/a/f503062219ae402e9cca27d6.html


https://juejin.cn/post/6844903806690557966

至少嘗試了三四種方法。

然后去google上面查找問題的答案,在stackoverflow上面找到一篇文件,解決了這個辦法。

https://stackoverflow.com/questions/10583622/com-google-zxing-notfoundexception-exception-comes-when-core-java-program-execut

原代碼如下:

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";
}

立馬進行測試,問題解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM