您的位置:首页 > 编程语言 > Java开发

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

2016-11-10 09:31 543 查看
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");

<
a6f7
span style="font-size:12px;">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 二维码 微信 zxing jar