生成条形码工具类:
package com.nancal.utils;
import cn.hutool.core.util.ObjectUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.*;
import com.google.zxing.pdf417.PDF417Writer;
import org.apache.commons.lang3.StringUtils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
/**
* 生成条形码(可显示文本内容)
*/
public class BarCodeUtils {
/**
* 设置条码的宽的白边
*/
private static final int WHITE_WIDTH = 10;
/**
* 默认图片宽度
*/
private static final int DEFAULT_PICTURE_WIDTH = 300;
/**
* 默认图片高度
*/
private static final int DEFAULT_PICTURE_HEIGHT = 200;
/**
* 默认条形码宽度
*/
private static final int DEFAULT_BAR_CODE_WIDTH = 200;
/**
* 默认条形码高度
*/
private static final int DEFAULT_BAR_CODE_HEIGHT = 70;
/**
* 默认字体大小
*/
private static final int DEFAULT_FONT_SIZE = 15;
/**
* 设置 条形码参数
*/
private static final Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
static {
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
}
/**
* 获取条形码图片
*
* @param codeValue 条形码内容
* @return 条形码图片
*/
public static BufferedImage getBarCodeImage(String codeValue) {
return getBarCodeImage(codeValue, DEFAULT_BAR_CODE_WIDTH, DEFAULT_BAR_CODE_HEIGHT);
}
/**
* 获取条形码图片
*
* @param codeValue 条形码内容
* @param width 宽度
* @param height 高度
* @return 条形码图片
*/
public static BufferedImage getBarCodeImage(String codeValue, int width, int height) {
// CODE_128是最常用的条形码格式
return getBarCodeImage(codeValue, width, height, BarcodeFormat.CODE_128);
}
/**
* 获取条形码图片
*
* @param codeValue 条形码内容
* @param width 宽度
* @param height 高度
* @param barcodeFormat 条形码编码格式
* @return 条形码图片
*/
public static BufferedImage getBarCodeImage(String codeValue, int width, int height, BarcodeFormat barcodeFormat) {
Writer writer;
switch (barcodeFormat) {
case CODE_128:
// 最常见的条形码,但是不支持中文
writer = new Code128Writer();
break;
case UPC_A:
// 支持中文的条形码格式
writer = new UPCAWriter();
break;
case UPC_E:
// 支持中文的条形码格式
writer = new UPCEWriter();
break;
case CODE_39:
// 支持中文的条形码格式
writer = new Code39Writer();
break;
case ITF:
// 支持中文的条形码格式
writer = new ITFWriter();
break;
case CODABAR:
// 支持中文的条形码格式
writer = new CodaBarWriter();
break;
case PDF_417:
// 支持中文的条形码格式
writer = new PDF417Writer();
break;
// 如果使用到其他格式,可以在这里添加
default:
writer = new Code128Writer();
}
// 编码内容, 编码类型, 宽度, 高度, 设置参数
BitMatrix bitMatrix;
try {
//设置codeWidth
hints.put(EncodeHintType.MARGIN, width);
bitMatrix = writer.encode(codeValue, barcodeFormat, width, height, hints);
} catch (WriterException e) {
throw new RuntimeException("条形码内容写入失败");
}
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
/**
* 获取条形码
*
* @param codeValue 条形码内容
* @param bottomStr 底部文字
* @return 图片
*/
public static BufferedImage getBarCodeWithWords(String codeValue, String bottomStr) {
return getBarCodeWithWords(codeValue, bottomStr, "", "", 0);
}
/**
* 获取条形码
*
* @param codeValue 条形码内容
* @param bottomStr 底部文字
* @param fontSize 字体大小
* @param barCodeWidth 码宽度
* @param barCodeHeight 码高度
* @return 图片
*/
public static BufferedImage getBarCodeWithWords(String codeValue, String bottomStr, int fontSize, int barCodeWidth, int barCodeHeight, BarcodeFormat format, int wordAndCodeSpacing) {
if (ObjectUtil.isEmpty(format)) {
format = BarcodeFormat.CODE_128;
}
int picHeight = DEFAULT_PICTURE_HEIGHT + wordAndCodeSpacing + fontSize * 2;
return getCodeWithWords(getBarCodeImage(codeValue, barCodeWidth, barCodeHeight, format), bottomStr, "", "", DEFAULT_PICTURE_WIDTH,
picHeight, 0, 0, 0, 0, 0, 0, fontSize, wordAndCodeSpacing);
}
/**
* 获取条形码
*
* @param codeValue 条形码内容
* @param bottomStr 底部文字
* @param topLeftStr 左上角文字
* @param topRightStr 右上角文字
* @return 图片
*/
public static BufferedImage getBarCodeWithWords(String codeValue, String bottomStr, String topLeftStr,
String topRightStr, int wordAndCodeSpacing) {
return getCodeWithWords(getBarCodeImage(codeValue), bottomStr, topLeftStr, topRightStr, DEFAULT_PICTURE_WIDTH,
DEFAULT_PICTURE_HEIGHT, 0, 0, 0, 0, 0, 0, DEFAULT_FONT_SIZE, wordAndCodeSpacing);
}
/**
* 获取条形码
*
* @param codeImage 条形码图片
* @param bottomStr 底部文字
* @param topLeftStr 左上角文字
* @param topRightStr 右上角文字
* @param pictureWidth 图片宽度
* @param pictureHeight 图片高度
* @param codeOffsetX 条形码宽度
* @param codeOffsetY 条形码高度
* @param topLeftOffsetX 左上角文字X轴偏移量
* @param topLeftOffsetY 左上角文字Y轴偏移量
* @param topRightOffsetX 右上角文字X轴偏移量
* @param topRightOffsetY 右上角文字Y轴偏移量
* @param fontSize 字体大小
* @return 条形码图片
*/
public static BufferedImage getCodeWithWords(BufferedImage codeImage, String bottomStr, String topLeftStr,
String topRightStr, int pictureWidth, int pictureHeight, int codeOffsetX, int codeOffsetY,
int topLeftOffsetX, int topLeftOffsetY, int topRightOffsetX, int topRightOffsetY, int fontSize, int wordAndCodeSpacing) {
pictureWidth = codeImage.getWidth() + WHITE_WIDTH;
BufferedImage picImage = new BufferedImage(pictureWidth, pictureHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = picImage.createGraphics();
// 抗锯齿
setGraphics2D(g2d);
// 设置白色
setColorWhite(g2d, picImage.getWidth(), picImage.getHeight());
// 条形码默认居中显示
int codeStartX = (pictureWidth - codeImage.getWidth()) / 2 + codeOffsetX;
// int codeStartY = (pictureHeight - codeImage.getHeight()) / 2 + codeOffsetY;
int codeStartY = 0;
// 画条形码到新的面板
g2d.drawImage(codeImage, codeStartX, codeStartY, codeImage.getWidth(), codeImage.getHeight(), null);
// 画文字到新的面板
g2d.setColor(Color.BLACK);
// 字体、字型、字号
g2d.setFont(new Font("微软雅黑", Font.PLAIN, fontSize));
// 文字与条形码之间的间隔
if (wordAndCodeSpacing == 0) {
wordAndCodeSpacing = 3;
}
if (StringUtils.isNotEmpty(bottomStr)) {
// 文字长度
int strWidth = g2d.getFontMetrics().stringWidth(bottomStr);
// 文字X轴开始坐标,这里是居中
int strStartX = codeStartX + (codeImage.getWidth() - strWidth) / 2;
// 文字Y轴开始坐标
int strStartY = codeStartY + codeImage.getHeight() + fontSize + wordAndCodeSpacing;
// 画文字
g2d.drawString(bottomStr, strStartX, strStartY);
}
if (StringUtils.isNotEmpty(topLeftStr)) {
// 文字长度
int strWidth = g2d.getFontMetrics().stringWidth(topLeftStr);
// 文字X轴开始坐标
int strStartX = codeStartX + topLeftOffsetX;
// 文字Y轴开始坐标
int strStartY = codeStartY + topLeftOffsetY - wordAndCodeSpacing;
// 画文字
g2d.drawString(topLeftStr, strStartX, strStartY);
}
if (StringUtils.isNotEmpty(topRightStr)) {
// 文字长度
int strWidth = g2d.getFontMetrics().stringWidth(topRightStr);
// 文字X轴开始坐标,这里是居中
int strStartX = codeStartX + codeImage.getWidth() - strWidth + topRightOffsetX;
// 文字Y轴开始坐标
int strStartY = codeStartY + topRightOffsetY - wordAndCodeSpacing;
// 画文字
g2d.drawString(topRightStr, strStartX, strStartY);
}
g2d.dispose();
picImage.flush();
return picImage;
}
/**
* 设置 Graphics2D 属性 (抗锯齿)
*
* @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setGraphics2D(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(s);
}
/**
* 设置背景为白色
*
* @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setColorWhite(Graphics2D g2d, int width, int height) {
g2d.setColor(Color.WHITE);
// 填充整个屏幕
g2d.fillRect(0, 0, width, height);
// 设置笔刷
g2d.setColor(Color.BLACK);
}
}
执行
public static void main(String[] args) throws IOException {
String context="你好";
String buttomStr="我是底部文字";
int fontSize = 15;
int width=4;
int height=1000;
BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;
int lineSpacing = 8;
BufferedImage image = BarCodeUtils.getBarCodeWithWords(context, buttomStr, fontSize, width, height, barcodeFormat, lineSpacing);
ImageIO.write(image, "jpg", new File("D:/aaa/bb.jpg"));
}
类似这几个参数入参生成条码
条码生成结果:
二维码util类
package com.nancal.utils;
import cn.hutool.core.util.ObjectUtil;
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;
import io.micrometer.core.instrument.util.StringUtils;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/*
* @Auther:fancc
* @Date: create in 2023/6/9 10:50
* @Description:二维码的生成工具类
*/
public class QRCodeUtils {
//CODE_WIDTH:二维码宽度,单位像素
private static final int CODE_WIDTH = 400;
//CODE_HEIGHT:二维码高度,单位像素
private static final int CODE_HEIGHT = 400;
//FRONT_COLOR:二维码前景色,0x000000 表示黑色
private static final int FRONT_COLOR = 0x000000;
//BACKGROUND_COLOR:二维码背景色,0xFFFFFF 表示白色
//演示用 16 进制表示,和前端页面 CSS 的取色是一样的,注意前后景颜色应该对比明显,如常见的黑白
private static final int BACKGROUND_COLOR = 0xFFFFFF;
public static void createCodeToFile(String content, File codeImgFileSaveDir, String fileName) {
try {
if (StringUtils.isBlank(content) || StringUtils.isBlank(fileName)) {
return;
}
content = content.trim();
if (codeImgFileSaveDir == null || codeImgFileSaveDir.isFile()) {
//二维码图片存在目录为空,默认放在桌面...
codeImgFileSaveDir = FileSystemView.getFileSystemView().getHomeDirectory();
}
if (!codeImgFileSaveDir.exists()) {
//二维码图片存在目录不存在,开始创建...
codeImgFileSaveDir.mkdirs();
}
//核心代码-生成二维码
BufferedImage bufferedImage = getBufferedImage(content);
File codeImgFile = new File(codeImgFileSaveDir, fileName);
ImageIO.write(bufferedImage, "png", codeImgFile);
System.out.println("二维码图片生成成功:" + codeImgFile.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成二维码并输出到输出流, 通常用于输出到网页上进行显示,输出到网页与输出到磁盘上的文件中,区别在于最后一句 ImageIO.write
* write(RenderedImage im,String formatName,File output):写到文件中
* write(RenderedImage im,String formatName,OutputStream output):输出到输出流中
*
* @param content :二维码内容
* @param outputStream :输出流,比如 HttpServletResponse 的 getOutputStream
*/
public static void createCodeToOutputStream(String content, OutputStream outputStream) {
try {
if (StringUtils.isBlank(content)) {
return;
}
content = content.trim();
//核心代码-生成二维码
BufferedImage bufferedImage = getBufferedImage(content);
//区别就是这一句,输出到输出流中,如果第三个参数是 File,则输出到文件中
ImageIO.write(bufferedImage, "png", outputStream);
System.out.println("二维码图片生成到输出流成功...");
} catch (Exception e) {
e.printStackTrace();
}
}
//核心代码-生成二维码
private static BufferedImage getBufferedImage(String content) throws WriterException {
//com.google.zxing.EncodeHintType:编码提示类型,枚举类型
Map<EncodeHintType, Object> hints = new HashMap();
//EncodeHintType.CHARACTER_SET:设置字符编码类型
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//EncodeHintType.ERROR_CORRECTION:设置误差校正
//ErrorCorrectionLevel:误差校正等级,L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
//不设置时,默认为 L 等级,等级不一样,生成的图案不同,但扫描的结果是一样的
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//EncodeHintType.MARGIN:设置二维码边距,单位像素,值越小,二维码距离四周越近
hints.put(EncodeHintType.MARGIN, 1);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < CODE_WIDTH; x++) {
for (int y = 0; y < CODE_HEIGHT; y++) {
bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
}
}
return bufferedImage;
}
//核心代码-生成二维码
/**
* 生成二维码
*
* @param content 内容
* @param format 码制
* @param codeWidth 正方形长宽一致
* @param level 容错等级
* @return 图片流
* @throws WriterException 写异常
*/
public static BufferedImage getBufferedImage(String content, BarcodeFormat format, int codeWidth, ErrorCorrectionLevel level) throws WriterException {
if (ObjectUtil.isEmpty(level)){
level = ErrorCorrectionLevel.L;
}
if (ObjectUtil.isEmpty(format)){
format = BarcodeFormat.QR_CODE;
}
//com.google.zxing.EncodeHintType:编码提示类型,枚举类型
Map<EncodeHintType, Object> hints = new HashMap();
//EncodeHintType.CHARACTER_SET:设置字符编码类型
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//EncodeHintType.ERROR_CORRECTION:设置误差校正
//ErrorCorrectionLevel:误差校正等级,L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
//不设置时,默认为 L 等级,等级不一样,生成的图案不同,但扫描的结果是一样的
hints.put(EncodeHintType.ERROR_CORRECTION, level);
//EncodeHintType.MARGIN:设置二维码边距,单位像素,值越小,二维码距离四周越近
hints.put(EncodeHintType.MARGIN, 1);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bitMatrix = multiFormatWriter.encode(content, format, codeWidth, codeWidth, hints);
BufferedImage bufferedImage = new BufferedImage(codeWidth, codeWidth, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < codeWidth; x++) {
for (int y = 0; y < codeWidth; y++) {
bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
}
}
return bufferedImage;
}
}