java生成二维码



package com.fl;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;

public class QRCodeEncoderHandler {
 public void encoderQRCode(String content, String imgPath) {
  try {
   Qrcode qrcodeHandler = new Qrcode();
   //
   qrcodeHandler.setQrcodeErrorCorrect('M');
   qrcodeHandler.setQrcodeEncodeMode('B');
   qrcodeHandler.setQrcodeVersion(5);
   byte[] contentBytes = content.getBytes("gb2312");
   BufferedImage bufImg = new BufferedImage(600, 600,
     BufferedImage.TYPE_INT_RGB);
   Graphics2D gs = bufImg.createGraphics();
   gs.setBackground(Color.WHITE);
   gs.clearRect(0, 0, 600, 600);
   gs.setColor(Color.BLACK);
   int pixoff = 2;
   if (contentBytes.length > 0 && contentBytes.length < 800) {
    boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
    for (int i = 0; i < codeOut.length; i++) {
     for (int j = 0; j < codeOut.length; j++) {
      if (codeOut[j][i]) {
       gs.fillRect(j * 16 + pixoff, i * 16 + pixoff, 16,
         16);
      }
     }
    }
   } else {
   }
   gs.dispose();
   bufImg.flush();
   File imgFile = new File(imgPath);
   ImageIO.write(bufImg, "png", imgFile);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  String imgPath = "G:\\" + "1234" + ".png";
  String content = "https://www.baidu.com/";
  QRCodeEncoderHandler hander = new QRCodeEncoderHandler();
  hander.encoderQRCode(content, imgPath);
  System.out.println("imgPath:" + imgPath);
 }
}

### 使用 Java 生成二维码 (QR Code) 在 Java生成二维码,最常用的方法是使用 **ZXing**(Zebra Crossing)库。ZXing 是一个开源的、跨平台的条形码和二维码生成与解析库,支持多种编码格式和纠错机制。 #### 1. Maven 依赖配置 首先,在 `pom.xml` 文件中添加 ZXing 的依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.5.2</version> </dependency> ``` #### 2. 生成二维码的核心代码 以下是一个简单的 Java 示例,展示如何使用 ZXing 生成二维码并将其保存为图像文件: ```java import com.google.zxing.*; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; public class QRCodeGenerator { public static void generateQRCode(String data, String filePath, int width, int height) throws WriterException, IOException { // 设置二维码的纠错级别 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height, com.google.zxing.EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 写入文件 Path path = FileSystems.getDefault().getPath(filePath); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); } public static void main(String[] args) { String data = "https://www.example.com"; String filePath = "qrcode.png"; int width = 300; int height = 300; try { generateQRCode(data, filePath, width, height); System.out.println("二维码生成成功!"); } catch (Exception e) { System.err.println("生成二维码失败:" + e.getMessage()); } } } ``` #### 3. 自定义二维码(添加 Logo) 如果希望在二维码中心添加 Logo,可以在生成二维码图像后,使用 `BufferedImage` 和 `Graphics2D` 将 Logo 叠加到二维码图像上: ```java import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; public class QRCodeWithLogo { public static void addLogoToQRCode(String qrCodePath, String logoPath, String outputFilePath, int logoSize) throws Exception { BufferedImage qrImage = ImageIO.read(new File(qrCodePath)); BufferedImage logo = ImageIO.read(new File(logoPath)); // 调整 Logo 大小 Image scaledLogo = logo.getScaledInstance(logoSize, logoSize, Image.SCALE_SMOOTH); BufferedImage resizedLogo = new BufferedImage(logoSize, logoSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g = resizedLogo.createGraphics(); g.drawImage(scaledLogo, 0, 0, null); g.dispose(); // 在二维码中心绘制 Logo Graphics2D graphics = qrImage.createGraphics(); int x = (qrImage.getWidth() - logoSize) / 2; int y = (qrImage.getHeight() - logoSize) / 2; graphics.drawImage(resizedLogo, x, y, null); graphics.dispose(); // 保存结果 ImageIO.write(qrImage, "PNG", new File(outputFilePath)); } public static void main(String[] args) throws Exception { String qrCodePath = "qrcode.png"; String logoPath = "logo.png"; String outputFilePath = "qrcode_with_logo.png"; int logoSize = 50; addLogoToQRCode(qrCodePath, logoPath, outputFilePath, logoSize); System.out.println("二维码添加 Logo 成功!"); } } ``` #### 4. 常见问题处理 在使用 ZXing 生成二维码时,可能会遇到如下异常: - **`data bits cannot fit in the QR Code`**:表示数据量超出了当前版本二维码的容量限制。可以通过提高二维码的版本(`Version`)或降低数据量来解决。例如,使用 `EncodeHintType.QR_VERSION` 设置更高的版本[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值