帮我写一段Java代码生成二维码,并二维码中心携带log,且log是彩色的,
时间: 2024-06-10 13:07:13 浏览: 129
生成、解析带logo的二维码(java)
好的,以下是Java代码生成带彩色logo的二维码:
```java
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
public class QRCodeGenerator {
public static void main(String[] args) {
String qrCodeText = "https://www.example.com";
String filePath = "qrcode.png";
String logoPath = "logo.png";
int size = 300;
try {
QRCodeWriter qrWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size);
BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix, getMatrixConfig());
BufferedImage logoImage = ImageIO.read(new File(logoPath));
Graphics2D graphics = qrImage.createGraphics();
int logoSize = size * 25 / 100;
// 设置logo的中心位置
int centerX = (qrImage.getWidth() - logoSize) / 2;
int centerY = (qrImage.getHeight() - logoSize) / 2;
graphics.drawImage(logoImage, centerX, centerY, logoSize, logoSize, null);
// 设置彩色logo
graphics.setPaint(Color.RED);
graphics.fillRoundRect(centerX, centerY, logoSize, logoSize, 50, 50);
graphics.setComposite(java.awt.AlphaComposite.SrcIn);
graphics.drawImage(logoImage, centerX, centerY, logoSize, logoSize, null);
ImageIO.write(qrImage, "png", new File(filePath));
System.out.println("QR Code with logo has been generated.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static MatrixToImageConfig getMatrixConfig() {
// 黑色背景, 白色前景
return new MatrixToImageConfig(0xFF000000, 0xFFFFFFFF);
}
}
```
这段代码会生成一个二维码,其中包含指定的文本,并将彩色的logo添加到二维码中间。你需要将logo命名为`logo.png`,并与代码放在同一目录下,二维码将保存在`qrcode.png`。
阅读全文