package com.qmth.boot.tools.zxing;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 条码图片解码工具
 */
public class BarcodeDecoder {

    private static Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>() {{
        // 指定深度尝试
        put(DecodeHintType.TRY_HARDER, true);
        // 指定编码格式
        put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
    }};

    /**
     * 识别条码内容
     *
     * @param ins      图片输入流
     * @param fallback 异常返回值，为null则抛出过程异常
     * @return 识别结果
     */
    public static String decode(InputStream ins, String fallback) {
        try {
            BinaryBitmap binaryBitmap = new BinaryBitmap(
                    new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(ins))));
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);
            return result.getText();
        } catch (Exception e) {
            if (fallback != null) {
                return fallback;
            } else {
                throw new RuntimeException("Barcode decode error", e);
            }
        }
    }
}
