java 使用zxing生成二维码,要求二维码上面生成可换行标题,返回BufferedImage
时间: 2024-01-28 14:21:11 浏览: 155
可以使用 zxing 的 MultiFormatWriter 类来生成二维码,要在二维码上方生成可换行标题,可以使用 BufferedImage 类来创建一个新的 BufferedImage 对象,并在上面绘制标题和二维码。具体代码如下:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class QRCodeUtil {
/**
* 生成带有标题的二维码
*
* @param content 二维码内容
* @param title 标题
* @param width 二维码宽度
* @param height 二维码高度
* @return 带有标题的二维码 BufferedImage 对象
*/
public static BufferedImage createQRCodeWithTitle(String content, String title, int width, int height) {
try {
// 生成二维码矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
// 获取二维码图片的宽高
int qrCodeWidth = bitMatrix.getWidth();
int qrCodeHeight = bitMatrix.getHeight();
// 新建一个 BufferedImage 对象
BufferedImage image = new BufferedImage(qrCodeWidth, qrCodeHeight + 50, BufferedImage.TYPE_INT_RGB);
// 在 BufferedImage 上绘制标题和二维码
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, qrCodeWidth, qrCodeHeight + 50);
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("宋体", Font.BOLD, 20));
String[] titleLines = title.split("\n");
int titleHeight = graphics.getFontMetrics().getHeight() * titleLines.length;
for(int i = 0; i < titleLines.length; i++) {
String titleLine = titleLines[i];
int titleWidth = graphics.getFontMetrics().stringWidth(titleLine);
int titleX = (qrCodeWidth - titleWidth) / 2;
int titleY = qrCodeHeight + 15 + i * graphics.getFontMetrics().getHeight();
graphics.drawString(titleLine, titleX, titleY);
}
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix qrCodeMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight);
for (int y = 0; y < qrCodeHeight; y++) {
int offset = y * qrCodeWidth;
for (int x = 0; x < qrCodeWidth; x++) {
image.setRGB(x, y + titleHeight, qrCodeMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
}
```
调用方式:
```java
BufferedImage image = QRCodeUtil.createQRCodeWithTitle("二维码内容", "标题\n换行", 400, 400);
ImageIO.write(image, "png", new File("qrcode.png"));
```
阅读全文