package com.yunfeiyun.agmp.common.utils.img;

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.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.EnumMap;
import java.util.Map;

public class BitMatrixUtil {

    private BitMatrixUtil(){

    }

    public static BufferedImage createBitMatrixUtil(String url,int width,int height,int margin) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
        hints.put(EncodeHintType.MARGIN,margin);
        BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, width, height,hints);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }
    public static BufferedImage createBarcode(String data,int width,int height,int lineWidth) throws Exception{
        Code128Writer writer = new Code128Writer();
        BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.CODE_128, width, height);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);
        g2d.setColor(Color.BLACK);
        int x1 = 0;
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            if (bitMatrix.get(x, 0)) {
                g2d.fillRect(x1, 0, lineWidth, height);
            }
            x1 =  x1  + lineWidth;
        }
        g2d.dispose();
        return image;
    }
}
