条形码/二维码之开源利器ZXing图文介绍(二)

2014-11-24 01:45:31 · 作者: · 浏览: 1
zer;

/**

* @blog http://sjsky.iteye.com

* @author Michael

*/

public class ZxingDecoderHandler {

/**

* @param imgPath

* @return String

*/

public String decode(String imgPath) {

BufferedImage image = null;

Result result = null;

try {

image = ImageIO.read(new File(imgPath));

if (image == null) {

System.out.println("the decode image may be not exit.");

}

LuminanceSource source = new BufferedImageLuminanceSource(image);

BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

Hashtable hints = new Hashtable();

hints.put(DecodeHintType.CHARACTER_SET, "GBK");

result = new MultiFormatReader().decode(bitmap, hints);

return result.getText();

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* @param args

*/

public static void main(String[] args) {

String imgPath = "d:/test/twocode/michael_zxing.png";

ZxingDecoderHandler handler = new ZxingDecoderHandler();

String decodeContent = handler.decode(imgPath);

System.out.println("解码内容如下:");

System.out.println(decodeContent);

System.out.println("Michael ,you have finished zxing decode.");

}

}

运行结果如下:

解码内容如下:

Hello Michael(大大),welcome to Zxing!

Michael’s blog [ http://sjsky.iteye.com ]

EMail [ sjsky007@gmail.com ]

Twitter [ @suncto ]

Michael ,you have finished zxing decode.

从测试结果可见:解码出的内容和之前编码的内容是一致

【三】、 条形码(EAN-13)的编码和解码演示:

3-1. 编码示例:

Java代码

package michael.zxing;

import java.io.File;

import com.google.zxing.BarcodeFormat;

import com.google.zxing.MultiFormatWriter;

import com.google.zxing.client.j2se.MatrixToImageWriter;

import com.google.zxing.common.BitMatrix;

/**

* @blog http://sjsky.iteye.com

* @author Michael

*/

public class ZxingEAN13EncoderHandler {

/**

* 编码

* @param contents

* @param width

* @param height

* @param imgPath

*/

public void encode(String contents, int width, int height, String imgPath) {

int codeWidth = 3 + // start guard

(7 * 6) + // left bars

5 + // middle guard

(7 * 6) + // right bars

3; // end guard

codeWidth = Math.max(codeWidth, width);

try {

BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,

BarcodeFormat.EAN_13, codeWidth, height, null);

MatrixToImageWriter

.writeToFile(bitMatrix, "png", new File(imgPath));

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* @param args

*/

public static void main(String[] args) {

String imgPath = "d:/test/twocode/zxing_EAN13.png";

// 益达无糖口香糖的条形码

String contents = "6923450657713";

int width = 105, height = 50;

ZxingEAN13EncoderHandler handler = new ZxingEAN13EncoderHandler();

handler.encode(contents, width, height, imgPath);

System.out.println("Michael ,you have finished zxing EAN13 encode.");

}

}

6