通过barcode4j生成
通过zxing生成
@Controller
@RequestMapping("/bar/{code}")
public class BarCodeController {
@RequestMapping(method = RequestMethod.GET)
public void show(@PathVariable("code") String code,
HttpServletRequest request, HttpServletResponse response)
throws ConfigurationException, BarcodeException, IOException {
DefaultConfiguration cfg = new DefaultConfiguration("barcode");
DefaultConfiguration child = new DefaultConfiguration("datamatrix"); //code128
DefaultConfiguration attr;
//attr= new DefaultConfiguration("height");
//attr.setValue("10");
cfg.addChild(child);
//child.addChild(attr);
attr = new DefaultConfiguration("module-width");
attr.setValue("0.6");
child.addChild(attr);
int orientation = 0;
int resolution = 300;
BarcodeUtil util = BarcodeUtil.getInstance();
BarcodeGenerator gen = util.createBarcodeGenerator(cfg);
ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
BitmapCanvasProvider bitmap = new BitmapCanvasProvider(bout,
MimeTypes.MIME_JPEG, resolution, BufferedImage.TYPE_BYTE_BINARY,
false, orientation);
gen.generateBarcode(bitmap,code);
try {
bitmap.finish();
} catch (IOException e) {
} finally {
try {
bout.close();
} catch (IOException e) {
}
}
response.setContentType(MimeTypes.MIME_JPEG);
response.setContentLength(bout.size());
response.getOutputStream().write(bout.toByteArray());
response.getOutputStream().flush();
}
}
通过zxing生成
package gov.rsj.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
/**
* @author fox
* @date 2012-3-22 下午3:12:33
* @version 1.0
* @description QRCODE 条形码 需要javase.jar和core.jar两个包
*/
@Controller
@RequestMapping("/qrbar/{code}")
public class QrBarCodeController {
@RequestMapping(method = RequestMethod.GET)
public void show(@PathVariable("code") String code,
HttpServletRequest request, HttpServletResponse response){
QRCodeWriter writer = new QRCodeWriter();
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
BitMatrix bitMatrix = null;
try {
bitMatrix = writer.encode(code, BarcodeFormat.QR_CODE, 300, 300);
MatrixToImageWriter.writeToStream(bitMatrix, "jpeg", response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}