二维码生成器

package org.example.cropland.controller;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeGenerator {

    public static void generateQRCodeImage(String text, int width, int height, String filePath, String logoPath)
            throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        // 创建二维码图片
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

        // 加载自定义图片
        BufferedImage logoImage = ImageIO.read(new File(logoPath));

        // 创建一个新的BufferedImage对象,用于合成二维码和自定义图片
        BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = combined.createGraphics();

        // 将二维码绘制到合成图片中
        g.drawImage(MatrixToImageWriter.toBufferedImage(bitMatrix), 0, 0, null);

        // 计算自定义图片的位置,使其居中显示在二维码中间
        int logoWidth = Math.min(logoImage.getWidth(), width / 6);
        int logoHeight = Math.min(logoImage.getHeight(), height / 6);
        int x = (width - logoWidth) / 2;
        int y = (height - logoHeight) / 2;

        // 合成二维码和自定义图片
        g.drawImage(logoImage, x, y, logoWidth, logoHeight, null);
        g.dispose();

        // 将合成的图片保存到文件
        ImageIO.write(combined, "PNG", new File(filePath));
    }

    public static void main(String[] args) {
        String websiteURL = "http://39.107.86.110:8080/login/login.html"; // 替换为你的网站链接
        int width = 600; // 图像宽度
        int height = 600; // 图像高度
        String QR_CODE_IMAGE_PATH = "E:\\code.jpg"; // 二维码保存路径
        String logoPath = "E:\\demo\\cropland\\src\\main\\resources\\static\\image\\1.jpg"; // 自定义图片路径
        try {
            generateQRCodeImage(websiteURL, width, height, QR_CODE_IMAGE_PATH, logoPath);
            System.out.println("二维码已生成到:" + QR_CODE_IMAGE_PATH);
        } catch (WriterException | IOException e) {
            System.out.println("创建二维码时出现错误:" + e.getMessage());
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值