最近需要完成一个二维码生成功能,使用了barcode4j进行开发。
ps:附件即为barcode4j的src包和bin包
生成代码如下:
- public class CodeService {
- private static CodeService instance;
- private static DefaultConfiguration cfg;
- /**
- * 二维码参数
- */
- private static final String FORMAT = MimeTypes.MIME_JPEG;
- private static final int ORIENTATION = 0;
- private static final int RESOLUTION = 300;
- private static final String BARCODE_TYPE = "datamatrix";
- private CodeService() {
- }
- public static CodeService getInstance() {
- if (instance == null) {
- instance = new CodeService();
- cfg = new DefaultConfiguration("barcode");
- DefaultConfiguration child = new DefaultConfiguration(BARCODE_TYPE );
- cfg.addChild(child);
- DefaultConfiguration attr;
- attr = new DefaultConfiguration("height");
- attr.setValue(50);
- child.addChild(attr);
- attr = new DefaultConfiguration("module-width");
- attr.setValue("0.6");
- child.addChild(attr);
- }
- return instance;
- }
- public InputStream getCodeImage(String code, String type) {
- InputStream ret = null;
- ByteArrayOutputStream baos = null;
- BitmapCanvasProvider bitmap = null;
- try {
- Configuration cfg = buildCfg(type);
- BarcodeUtil util = BarcodeUtil.getInstance();
- BarcodeGenerator gen = util.createBarcodeGenerator(cfg);
- baos = new ByteArrayOutputStream(4096);
- bitmap = new BitmapCanvasProvider(baos, FORMAT, RESOLUTION, BufferedImage.TYPE_BYTE_GRAY, true, ORIENTATION);
- gen.generateBarcode(bitmap, code);
- bitmap.finish();
- ret = FileUtil.getInputStreamFromBytes(baos.toByteArray());
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (baos != null) {
- baos.close();
- }
- bitmap = null;
- } catch (Exception e) {
- }
- }
- return ret;
- }
- private Configuration buildCfg(String type) {
- return cfg;
- }
这个方法使用了datamatrix的二维码生成算法,qr算法二维码似乎这个组件并不支持生成。
ps:调整二维码生成图片大小,需要设置的参数为module-width,设置height不起作用。