package com.qmth.boot.tools.zxing;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.qmth.boot.tools.models.ByteArray;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 条码图片生成工具
 */
public class BarcodeEncoder {

    private static final String DEFAULT_IMAGE_TYPE = "png";

    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {{
        // 指定纠错等级
        put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 指定编码格式
        put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
    }};

    /**
     * 根据指定内容生成条码图片，默认格式为PNG
     *
     * @param content 条码内容
     * @param width   图片长度
     * @param height  图片高度
     * @return 图片数据流
     * @throws WriterException
     * @throws IOException
     */
    public static ByteArray encode(String content, int width, int height) throws WriterException, IOException {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, DEFAULT_IMAGE_TYPE, ous);
        return ByteArray.fromArray(ous.toByteArray());
    }
}
