Java二維碼生成和解析
阿新 • • 發佈:2019-02-13
二維碼生成:
引用的包: <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>
生成程式碼: /** * * @Title: createQrCodeByStringName * @param @param path 生成二維碼路徑 * @param @param name 二維碼名稱 * @param @param content 二維碼儲存的資訊 * @param @param qrCodeSize 二維碼長度和寬度 * @param @param imageFormat 圖片型別 * @param @throws WriterException * @param @throws IOException 設定檔案 * @return void 返回型別 * @throws */ public static void createQrCodeByStringName(String path,String name, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException{ FileOutputStream outputStream = new FileOutputStream(new File(path+name)); Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);// 生成矩陣 MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, outputStream);// 輸出影象 System.out.println("二維碼生成成功."); }
二維碼解析: /** * 讀二維碼並輸出攜帶的資訊 */ public static void readQrCode(FileInputStream inputStream) throws IOException{ BufferedImage image; try { image = ImageIO.read(inputStream); LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 對影象進行解碼 System.out.println("二維碼掃描結果:"+result.getText()); } catch (IOException e) { e.printStackTrace(); } catch (NotFoundException e) { e.printStackTrace(); } }
測試程式碼:
/**
* 測試程式碼
* @throws WriterException
* @throws ParseException
*/
public static void main(String[] args) throws IOException, WriterException, ParseException {
createQrCodeByStringName("d:\\","www.jpg","哈哈哈哈",500,"JPEG");
readQrCode(new FileInputStream(new File("d:\\www.jpg")));
}