在之前一篇文章,详细介绍了利用Zxing生成QRCode二维码以及BarCode条形码,并可以输出到文件或者输出到网页,很多时候,我们生成的二维码中间需要加一个logo图片,本次我们演示如何做:
一些依赖等基础准备工作,就不介绍了,如有需求,可以看:https://blog.terrynow.com/2021/02/06/java-google-zxing-generate-qrcode-or-barcode-output-to-file-or-web/
以读取一张logo的图片文件,生成到文件为例,说明详见代码注释
public static void main(String[] args) throws Exception {
int qrWithAndHeight = 800; // 生成QRCode的图片长宽,假设时正方形
int logoWithAndHeight = 80; // 嵌入的Logo的图片长宽,实际的logo图片可以比这个大,比这个小就不清晰
String qrContent = "https://blog.terrynow.com"; // 实际QR扫出来的内容
BufferedImage qrCodeImage = generateQRCode(qrContent, qrWithAndHeight);
// 准备画图
Graphics2D g = qrCodeImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// 读取logo文件,计算正中央的位置,画到qrCode图片中去
Image logoImage = ImageIO.read(new File("/Users/Terry/Pictures/logo.jpg"));
int logoXOrY = (qrWithAndHeight - logoWithAndHeight) / 2;
g.drawImage(logoImage, logoXOrY, logoXOrY, logoWithAndHeight, logoWithAndHeight, null);
g.dispose();
//保存到文件,如需输出到网页,请看 https://blog.terrynow.com/2021/02/06/java-google-zxing-generate-qrcode-or-barcode-output-to-file-or-web/
ImageIO.write(qrCodeImage, "jpeg", new File("/Users/Terry/Downloads/qrcode.jpg"));
}
public static BufferedImage generateQRCode(String content, int widthAndHeight) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 2);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints);
return toBufferedImage(bitMatrix);
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int black = 0xFF000000;//用于设置图案的颜色
int white = 0xFFFFFFFF; //用于背景色
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, (matrix.get(x, y) ? black : white));
// image.setRGB(x, y, (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
}
}
return image;
}
如图,一个带logo的二维码就做好啦
更多开发和运维过程中遇到的坑已经解决问题的方案、干货分享请访问 https://blog.terrynow.com/