package com.shzg.project.unique.unit;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.client.j2se.MatrixToImageWriter;

public class QrCodeUtils
{
    public static String generateBase64(String text)
    {
        try
        {
            int width = 200;
            int height = 200;

            BitMatrix matrix = new MultiFormatWriter()
                    .encode(text, BarcodeFormat.QR_CODE, width, height);

            BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);

            return "data:image/png;base64," +
                    Base64.getEncoder().encodeToString(stream.toByteArray());
        }
        catch (Exception e)
        {
            throw new RuntimeException("二维码生成失败", e);
        }
    }
}