一、問題由來
自己在做一個小程式專案的後臺,其中需要使用到識別圖片二維碼資訊,而且是必須在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";
}
立馬進行測試,問題解決。