public static void encode(String content, String format, String filePath) {
try {
Hashtable hints = new Hashtable();//設(shè)置編碼類型
hints.put(EncodeHintType.CHARACTER_SET, DEFAULT_ENCODING);
//編碼
BitMatrix bitMatrix = new QRCodeWriter().encode(content,
BarcodeFormat.QR_CODE, DEFAULT_IMAGE_WIDTH,
DEFAULT_IMAGE_HEIGHT,hints);
//輸出到文件,也可以輸出到流
File file = new File(filePath);
MatrixToImageWriter.writeToFile(bitMatrix, format, file);
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e1) {
e1.printStackTrace();
}
}
解碼:
BufferedImage image = ImageIO.read(file);//讀取文件
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
source));
//解碼
Result result = new MultiFormatReader().decode(bitmap);
String resultStr = result.getText();
System.out.println(resultStr);