package shop.alien.util.qrcode;

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 java.io.File;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * 生成二维码
 *
 * @author ssk
 */
public class CreateQrCodeDemo1Util {

    public static void main(String[] args) {
        createQRCode("ssr://MzQuODAuMTMyLjEzOjQ0MzphdXRoX2FlczEyOF9tZDU6YWVzLTI1Ni1jZmI6dGxzMS4yX3RpY2tldF9hdXRoOmMzTnJNVGN5TXpnd01UazU");
    }

    /**
     * @param content 二维码内容
     * @return 文件名
     */
    public static String createQRCode(String content) {
        String fileName = "";
        //宽高
        final int width = 500;
        final int height = 500;
        //图片类型
        final String format = "png";
        // 定义二维码的参数
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 格式化时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            fileName = sdf.format(date);
            Path file = new File("D:/" + fileName + ".png").toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
            System.out.println(file);
            System.out.println("二维码生成成功");
        } catch (Exception e) {
            System.out.println("二维码生成错误");
        }
        return fileName;
    }
}
