package com.house365.web.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Hashtable;

/**
 * 根据url生产二维码
 * @author huang xiner
 * @version 1.0
 * @date 2021/5/25 10:44
 */
public class QrCodeUtil {
    private final static Logger logger = LoggerFactory.getLogger(QrCodeUtil.class.getName());
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    private static final int WIDTH = 750;
    private static final int HEIGHT = 750;

    /**
     * 功能描述：生成二维码字节数组
     * @param content 文本内容
     * @return
     */
    public static byte[] createImg(String content) throws Exception{
        byte[] data = null;
        File tempFile = null;
        FileInputStream input = null;
        ByteArrayOutputStream output = null;
        try {
            output = new ByteArrayOutputStream();
            tempFile = File.createTempFile("temp", null);
            //生成临时图片
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            MatrixToImageWriter.writeToFile(matrix, "png", tempFile);
            //图片转储字节数组
            input = new FileInputStream(tempFile);
            byte[] temp = new byte[1000];
            int n;
            while ((n = input.read(temp)) != -1) {
                output.write(temp, 0, n);
            }
            data = output.toByteArray();
            logger.info("根据内容{}创建二维码成功",content);
        } catch (Exception ex) {
            throw new Exception("生成二维码图片异常",ex);
        } finally {
            try {
                if(input!=null)
                    input.close();
                if(output!=null)
                    output.close();
            } catch (IOException ex) {
                logger.error("创建二维码成功,文件流关闭异常",ex);
            }
            if (tempFile != null)
                tempFile.delete();
        }
        return data;
    }
}
