package com.qmth.paper.library.common.util;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.common.HybridBinarizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

/**
 * 条形码识别工具
 */
public class BarCodeUtils {

    private static final Logger logger = LoggerFactory.getLogger(BarCodeUtils.class);

    /**
     * zxing 解码条码
     *
     * @param file 文件名
     * @return
     */
    public static String decode(File file) throws IOException {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        return decode(image);
    }

    /**
     * zxing 解码条码
     *
     * @param image
     * @return
     */
    public static String decode(BufferedImage image) {
        String resultStr = null;
        try {
            BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            com.google.zxing.Result result;
            Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
            result = new MultiFormatReader().decode(bitmap, hints);
            resultStr = result.getText();
        } catch (NotFoundException e) {
            logger.error("未正确识别条码内容");
        }
        return resultStr;
    }

    public static void main(String[] args) throws Exception {
        File file = new File("/Users/xiaofei/Downloads/a34e586b6d3667d766a87285d64d3827.jpeg");
        String decode = BarCodeUtils.decode(file);
        System.out.println(decode);

    }

}
