1.引入pom依赖包
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j-light</artifactId>
<version>2.0</version>
</dependency>
2.java代码实现生成条形码
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import sun.misc.BASE64Encoder;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* 生成条形码
*/
public class BarcodeUtils {
/**
* 生成条形码文件
*
* @param msg 条形码的文本内容
* @param path 生成条形码的文件路径
* @return
*/
public static File generateFile(String msg, String path) {
File file = new File(path);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
generateBarCode128(msg, 5.0, 0.3, true, false, outputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
return file;
}
/**
* 生成code128条形码
*
* @param message 要生成的文本
* @param height 条形码的高度
* @param width 条形码的宽度
* @param withQuietZone 是否两边留白
* @param hideText 隐藏可读文本
* @param outputStream 输出流
*/
public static void generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText, OutputStream outputStream) {
Code128Bean bean = new Code128Bean();
// 分辨率,越大条形码就越大
int dpi = 150;
// 设置两侧是否留白
bean.doQuietZone(withQuietZone);
// 设置条形码高度和宽度
bean.setBarHeight(height);
if (width != null) {
bean.setModuleWidth(width);
}
// 设置文本位置(包括是否显示)
if (hideText) {
bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
}
// 设置图片类型
String format = "image/png";
BitmapCanvasProvider canvas = new BitmapCanvasProvider(outputStream, format, dpi,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
// 生成条形码
bean.generateBarcode(canvas, message);
try {
canvas.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String msg = "FH20220008";
//生成条形码路径
String path = "E:\\barcode1.png";
generateFile(msg, path);
try {
//条形码
ByteArrayOutputStream data = new ByteArrayOutputStream();
byte[] by = new byte[1024];
File file = new File(path);
InputStream in = new FileInputStream(file);
//将内容读取内存中
int len = -1;
while ((len = in.read(by)) != -1) {
data.write(by, 0, len);
}
//关闭流
in.close();
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(data.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}
}
文章来源地址https://www.toymoban.com/news/detail-830602.html
文章来源:https://www.toymoban.com/news/detail-830602.html
到了这里,关于java代码实现生成条形码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!