解决低版本 ZXING生成二维码图片白框太大的问题

最近项目里需要生成一些二维码,生产环境 jdk 1.6 无法支持高版本 zxing ,使用 core-2.3.0.jar 配合 javase-2.2jar,使用之后发现一些问题,生成之后的图片,白色边框区域太大了,导致二维码内容区域太小。 
百度了一下,有人说设置EncodeHintType.MARGIN属性即可,这个属性值为1-4,实际 测试 发现并没有什么卵用。(顺便说一下,一些比较老的版本中,这个EncodeHintType只有CHARACTER_SET和ERROR_CORRECTION两种属性设置,比较新的库才新增了其他属性,我这里使用的是2.3版本) 

后来找到另外一个解决办法:自己手动去除黑边,主要代码如下:

public void create(int width,String content,String wjid) throws Exception {
String filePath = System.getProperty("java.io.tmpdir") + "\\QRCode" + "\\";
String fileName = wjid + ".png";
int height = width;
//height = width;
String format = "png";// 图像类型
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, 1);
File file = new File(filePath + fileName);
BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
//设置默认 5 个像素 白边
matrix = deleteWhite(matrix,5);//白边
MatrixToImageWriter.writeToFile(matrix, format, file);
System.out.println("输出成功.");
}

//设置任意白边宽度 必须大于0
private static BitMatrix deleteWhite(BitMatrix matrix,int white) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1 + white * 2;
int resHeight = rec[3] + 1 + white *2;

BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
//resMatrix.setRegion(-2,-2,resWidth, resHeight);
resMatrix.clear();

for (int i = 0; i < resWidth - white * 2 ; i++) {
for (int j = 0; j < resHeight - white * 2 ; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i + white, j + white);
}
}
return resMatrix;
}


 完整代码及相关jar 包连接:http://download.csdn.net/detail/zengwenbo225566/9810762

你可能感兴趣的:(二维码,二维码,ZXing,白边太大问题)