应用barcode4j生成二维码

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qhl100/article/details/84759043
最近需要完成一个二维码生成功能,使用了barcode4j进行开发。


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;
}
展开阅读全文

没有更多推荐了,返回首页