java二维码之利用谷歌的zxing生成二维码,解析二维码
生成二维码
@RequestMapping("/123")
public void test(HttpServletRequest request,HttpServletResponse response){
// TODO Auto-generated method stub
int width=300;//宽
int height=300;//高
String format="png";
String content="http://www.baidu.com";
HashMap map = new HashMap<>();
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,map);
Path file = new File(request.getContextPath()+"/code").toPath();//二维码存放路径
MatrixToImageWriter.writeToPath(bitMatrix, format, file); //ImageIO.write(bufferedImage, "png", outputStream);
} catch (Exception e) {
}
}
解析二维码
/** * 解析二维码 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { MultiFormatReader formatReader = new MultiFormatReader(); File file = new File("D:/code/img.png");//要解析的二维码图片 BufferedImage bufferedImage = ImageIO.read(file); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage))); Map map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); Result result = formatReader.decode(binaryBitmap,map); System.out.println(result.getText());//内容 System.err.println(new Date(result.getTimestamp()));//时间 System.out.println(result.getBarcodeFormat());//二维码格式 }