package com.xjrsoft.common.utils;

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 javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;

public class QrCodeUtil {

	private static ByteArrayInputStream create(String url, int width, int height, int margin) throws Exception{
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, margin);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);

		ByteArrayInputStream input = new ByteArrayInputStream(stream.toByteArray());
        return input;
	}

	/**
	 * @param url 链接地址
	 * @param width 二维码的宽度
	 * @param height 二维码的高度
	 * @param margin 边距，只能是整数
	 * @return 返回png格式的BufferedImage
	 * @throws Exception
	 */
	public static BufferedImage createBufferedImage(String url, int width, int height, int margin) throws Exception{
		ByteArrayInputStream input = create(url, width, height, margin);
		return ImageIO.read(input);
	}

	/**
	 * @param url 链接地址
	 * @param width 二维码的宽度
	 * @param height 二维码的高度
	 * @param margin 边距，只能是整数
	 * @return 返回png格式的Base64
	 * @throws Exception
	 */
	public static String createBase64(String url, int width, int height, int margin) throws Exception{
		ByteArrayInputStream input = create(url, width, height, margin);
		byte[] bytes = new byte[1024];
		input.read(bytes);
		Base64.Encoder encoder = Base64.getEncoder();
		String QRCodeBase64 = encoder.encodeToString(bytes);
		return QRCodeBase64;
	}
}
