package com.tzy.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.tzy.common.exception.ServiceException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class BarcodeUtil {

    /**
     * 条形码识别
     * @param file
     * @return
     */
    public static String decodeBarcodeByFile(File file) {
        try {
            // 读取图片
            BufferedImage bufferedImage = ImageIO.read(file);
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            // 解码条形码
            Result result = new MultiFormatReader().decode(bitmap);
            return result.getText();
        } catch (Exception e) {
            throw new ServiceException("识别失败,请重试");
        }
    }

    public static String decodeBarcode(BufferedImage bufferedImage) {
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = new MultiFormatReader().decode(bitmap);
            return result.getText();
        } catch (Exception e) {
            throw new ServiceException("识别失败,请重试");
        }
    }

    // 使用ZXing解析二维码
    public static String decodeQRCode(BufferedImage bufferedImage) {
        QRCodeReader qrCodeReader = new QRCodeReader();
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Map<DecodeHintType, Object> hintMap = new HashMap<>();
            hintMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);  // 尝试更努力的解码
            Result result = qrCodeReader.decode(bitmap, hintMap);
            return result.getText();
        } catch (Exception e) {
            return null;
        }
    }
}
