使用java程序生成二维码以及中文乱码解决问题
因为是maven工程,所以先去idea中配置了maven的选项。添加了生成二维码所需要的依赖。
com.google.zxingcore3.3.0com.google.zxingjavase3.3.0核心代码片段
privatestaticvoidgenerateQRCodeImage(Stringtext,intwidth,intheight,StringfilePath)throwsWriterException,IOException{QRCodeWriterqrCodeWriter=newQRCodeWriter();BitMatrixbitMatrix=qrCodeWriter.encode(text,BarcodeFormat.QR_CODE,width,height);Pathpath=FileSystems.getDefault().getPath(filePath);MatrixToImageWriter.writeToPath(bitMatrix,"PNG",path);}调用此方法并传入二维码相关的参数既能获取二维码。值得注意的是如果内容是中文,需要设置字符编号才能正常显示。
privatestaticvoidgenerateQRCodeImage(Stringtext,intwidth,intheight,StringfilePath)throwsWriterException,IOException{QRCodeWriterqrCodeWriter=newQRCodeWriter();HashMaphints=newHashMap();hints.put(EncodeHintType.CHARACTER_SET,"utf-8");BitMatrixbitMatrix=qrCodeWriter.encode(text,BarcodeFormat.QR_CODE,width,height,hints);//BitMatrixbitMatrix=qrCodeWriter.encode(text,BarcodeFormat.QR_CODE,width,height);Pathpath=FileSystems.getDefault().getPath(filePath);MatrixToImageWriter.writeToPath(bitMatrix,"PNG",path);}这是设置字符编码之后的代码。如下是生成的二维码图片