Java讀取二維條碼
阿新 • • 發佈:2019-01-01
package com.laning.qrcode; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import javax.imageio.ImageIO; import com.google.zxing.Binarizer; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; public class ReaderQRCode { public static void main(String[] args) { File dstqrcode = new File("E:/大一課程/java程式設計/JAVA生成二維碼jar包/2.png"); try { readQRCode(dstqrcode); } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 1 讀取圖片 * 2轉化為亮度資料來源 * 3使用轉換器把亮度資料來源轉換為二進位制位數 * 4再把二進位制位資料在換為二進位制點陣圖 * 5讀取內容 * @throws IOException * @throws NotFoundException */ //讀取二維碼的工具方法 private static void readQRCode(File dstqrcode) throws IOException, NotFoundException{ //1 讀取圖片 BufferedImage img = ImageIO.read(dstqrcode); //2轉化為亮度資料來源 LuminanceSource有四個實現類,可以去官網查 LuminanceSource luminnanceSource = new BufferedImageLuminanceSource(img); //3使用轉換器把亮度資料來源轉換為二進位制位數 Binarizer binarizer = new HybridBinarizer(luminnanceSource); //4再把二進位制位資料在換為二進位制點陣圖 BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); //5讀取內容 MultiFormatReader formatReader = new MultiFormatReader(); HashMap<DecodeHintType,Object> hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET,"utf-8"); Result decode = formatReader.decode(binaryBitmap, hints); System.out.println(decode.getText()); } }