Java实现二维码-使用Zxing生成二维码

1、下载jar压缩包: https://github.com/zxing/
2、把解压后的文件core和javase下的com包都放在Eclipse下的Java项目中,使用Eclipse的导出Zxing3.3.0.jar

3、创建项目,将jar包导入,创建类。

------------------------------------------------------------------------------------------------------------------------------------------------------------

//生成二维码的类
public class CreateQRCode {
public static void main(String[] args) {
//定义图片高度和宽度
int width = 300;
int height = 300;
//指定图片格式
String format = "png";
//内容
String content = "神耐心";
//定义二维码的参数
HashMap hashMap = new HashMap();
hashMap.put(EncodeHintType.CHARACTER_SET,"UTF-8" );//字符编码
hashMap.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);//纠错等级
hashMap.put(EncodeHintType.MARGIN,2);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hashMap);
Path file = new File("D:/code/img.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------
//读取二维码内容
public class ReadQRCode {
public static void main(String[] args){
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File("D:/code/img.png");
BufferedImage image;
try {
image = ImageIO.read(file);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
HashMap hashMap = new HashMap();
hashMap.put(EncodeHintType.CHARACTER_SET,"UTF-8" );//字符编码
Result result = formatReader.decode(bitmap,hashMap);
System.out.println("解析结果:"+result.toString());
System.out.println("二维码格式:"+result.getBarcodeFormat());
System.out.println("二维码文本内容:"+result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}

你可能感兴趣的:(用java实现二维码)