java 生成二维码有很多开发的jar包如zxing,qrcode.q前者是谷歌开发的后者则是小日本开发的,
这里我们使用zxing的开发包来弄
1、先下载zxing开发包,这里用到的只是core那个jar包 (core-3.1.0.jar)
下载地址:http://download.youkuaiyun.com/download/u014733374/8212455
2、使用zxing开发还需要一个类,代码如下
public class ZxingEAN13EncoderHandler {
//contents:条形码内容;width:条形码宽度;height:条形码高度;imgPath:生成的条形码的存放路径
public String 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));
//在服务器上存放条形码的图片路径
String findPicture = "http://m.aicailang.com:7001/upload/" + userId +".jpg";
return findPicture ;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String imgPath = "d:/2.png";
// 益达无糖口香糖的条形码
String contents = "6923450657713";
int width = 105, height = 50;
ZxingEAN13EncoderHandler handler = new ZxingEAN13EncoderHandler();
//gettxm就是返回的条形码的编码图片
String gettxm = handler.encode(contents, width, height, imgPath);
}
}
3、上面的将内容编码成条形码图片格式,下面是将编码以后的条形码图片中的内容解码出来
public class ZxingEAN13DecoderHandler {
/**
* @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));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param args
*/
public static void main(String[] args) {
String imgPath = "d:/2.png";//存放条形码图片的路径
ZxingEAN13DecoderHandler handler = new ZxingEAN13DecoderHandler();
String decodeContent = handler.decode(imgPath);//将条形码图片的内容解析出来为一个字符串
System.out.println("解码内容如下:");
System.out.println(decodeContent);
}
}