帮我写一段Java代码生成二维码,并二维码中心携带log,log是我传进入的照片
时间: 2024-05-15 10:14:46 浏览: 80
当然,我可以帮您写一段Java代码生成带有logo的二维码。以下是代码示例:
```
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.client.j2se.MatrixToImageWriter;
public class QrCodeGenerator {
public static void generateQrCode(String text, String filePath, String logoPath) throws Exception {
QRCodeWriter qrWriter = new QRCodeWriter();
BitMatrix qrMatrix = qrWriter.encode(text, BarcodeFormat.QR_CODE, 300, 300);
BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(qrMatrix);
Graphics2D g2 = qrImage.createGraphics();
// 设置logo
BufferedImage logoImage = ImageIO.read(new File(logoPath));
int logoWidth = logoImage.getWidth(null) > qrImage.getWidth() * 2 / 10 ? (qrImage.getWidth() * 2 / 10) : logoImage.getWidth(null);
int logoHeight = logoImage.getHeight(null) > qrImage.getHeight() * 2 / 10 ? (qrImage.getHeight() * 2 / 10) : logoImage.getHeight(null);
int x = (qrImage.getWidth() - logoWidth) / 2;
int y = (qrImage.getHeight() - logoHeight) / 2;
g2.drawImage(logoImage, x , y , logoWidth, logoHeight, null);
g2.setColor(Color.BLACK);
g2.drawRect(x , y , logoWidth, logoHeight);
g2.dispose();
//生成二维码
File qrImgFile = new File(filePath);
ImageIO.write(qrImage, "png", qrImgFile);
}
}
```
您只需要传入二维码的内容、保存路径和logo图片的路径即可。其中,logo会自动居中并自适应缩放大小。希望这段代码能够帮到您。
阅读全文