1.Maven引入barcode4j依赖
<!-- 条形码生成 -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.avalon.framework/avalon-framework-api -->
<dependency>
<groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-api</artifactId>
<version>4.3.1</version>
</dependency>
2.工具类
package com.wulianwang.manage.utils.util;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.commons.io.FileUtils;
import org.krysalis.barcode4j.BarcodeException;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* 条形码工具类
*/
public class BarCodeUtils {
/**************************** 条形码 ********************************/
/**
* 生成code128条形码
*
* @param message 要生成的文本
* @param withQuietZone 是否两边留白
* @param hideText 隐藏可读文本
* @param filePath 文件生成的路径
*/
public static void generateBarCode128(String message, boolean withQuietZone, boolean hideText, String filePath) {
Code128Bean bean = new Code128Bean();
// 分辨率
int dpi = 512;
// 设置两侧是否留白
bean.doQuietZone(withQuietZone);
// 设置条形码高度和宽度(不填就是默认的)
// bean.setBarHeight((double) ObjectUtils.defaultIfNull(height, 9.0D));
// if (width != null) {
// bean.setModuleWidth(width);
// }
// 设置文本位置(包括是否显示)
if (hideText) {
bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
}
// 设置图片类型
String format = "image/png";
ByteArrayOutputStream ous = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
// 生产条形码
bean.generateBarcode(canvas, message);
try {
canvas.finish();
//字节码
byte[] bytes = ous.toByteArray();
FileUtils.writeByteArrayToFile(new File(filePath), bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
/**************************** 二维码 ********************************/
/**
* 生成二维码
* @param message 要生成的文本
* @param filePath 文件生成的路径
*/
public static void genQRCode(String message, String filePath){
try {
BarcodeUtil util = BarcodeUtil.getInstance();
DefaultConfiguration cfg = new DefaultConfiguration("barcode");
// Bar code type
DefaultConfiguration child = new DefaultConfiguration("datamatrix");
cfg.addChild(child);
// Human readable text position
DefaultConfiguration attr = new DefaultConfiguration("human-readable");
// //设置高度(无效果)
// attr = new DefaultConfiguration("height");
// attr.setValue(50);
// child.addChild(attr);
//设置二维码宽度
attr = new DefaultConfiguration("module-width");
attr.setValue("2.0");
child.addChild(attr);
BarcodeGenerator gen = util.createBarcodeGenerator(cfg);
//分辨率
int resolution = 300;
// 设置图片类型
String format = "image/png";
ByteArrayOutputStream ous = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, resolution,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
gen.generateBarcode(canvas, message);
canvas.finish();
//字节码
byte[] bytes = ous.toByteArray();
FileUtils.writeByteArrayToFile(new File(filePath), bytes);
} catch (ConfigurationException e) {
e.printStackTrace();
} catch (BarcodeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.调用工具类测试一下
@org.junit.Test
public void test1() throws IOException {
BarCodeUtils.generateBarCode128("V000001", true, false,"./bbb.jpg");
}
4.生成条形码图片
二维码
生成带logo的二维码
import java.util.Objects;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 画制定logo和制定描述的二维码
依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
*/
public class QrCodeUtil {
private static final int QRCOLOR = 0xFF000000; // 默认是黑色
private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
private static final int WIDTH = 400; // 二维码宽
private static final int HEIGHT = 400; // 二维码高
// 用于设置QR二维码参数
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
put(EncodeHintType.MARGIN, 0);
}
};
public static void main(String[] args) throws WriterException {
File logoFile = new File("D://QrCode/logo3.png");
File QrCodeFile = new File("D://QrCode/05.png");
String url = "http://ganyintao.top/";
String note = "在下老甘";
drawLogoQRCode(logoFile, QrCodeFile, url, note);
}
// 生成带logo的二维码图片
public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl, String note) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
}
}
int width = image.getWidth();
int height = image.getHeight();
if (Objects.nonNull(logoFile) && logoFile.exists()) {
// 构建绘图对象
Graphics2D g = image.createGraphics();
// 读取Logo图片
BufferedImage logo = ImageIO.read(logoFile);
// 开始绘制logo图片
g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
g.dispose();
logo.flush();
}
// 自定义文本描述
if (StringUtils.isNotEmpty(note)) {
// 新的图片,把带logo的二维码下面加上文字
BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D outg = outImage.createGraphics();
// 画二维码到新的面板
outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// 画文字到新的面板
outg.setColor(Color.BLACK);
outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
int strWidth = outg.getFontMetrics().stringWidth(note);
if (strWidth > 399) {
// //长度过长就截取前面部分
// 长度过长就换行
String note1 = note.substring(0, note.length() / 2);
String note2 = note.substring(note.length() / 2, note.length());
int strWidth1 = outg.getFontMetrics().stringWidth(note1);
int strWidth2 = outg.getFontMetrics().stringWidth(note2);
outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D outg2 = outImage2.createGraphics();
outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
outg2.setColor(Color.BLACK);
outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
outg2.drawString(note2, 200 - strWidth2 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
outg2.dispose();
outImage2.flush();
outImage = outImage2;
} else {
outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
}
outg.dispose();
outImage.flush();
image = outImage;
}
image.flush();
ImageIO.write(image, "png", codeFile); // TODO
} catch (Exception e) {
e.printStackTrace();
}
}
}