MatchService.java 2.7 KB
package com.viontech.match.service;

import com.viontech.keliu.i18n.util.LocalMessageUtil;
import com.viontech.keliu.websocket.AlgApiClient;
import com.viontech.match.entity.MatchResult;
import com.viontech.match.entity.Person;
import com.viontech.match.entity.vo.RequestData;
import com.viontech.match.util.Utils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * .
 *
 * @author 谢明辉
 * @date 2020/11/23
 */
@Service
public class MatchService {

    @Resource
    private AlgApiClient algApiClientFeature;
    @Resource
    private AlgService algService;

    public List<MatchResult> match(RequestData requestData) throws Exception {
        MultipartFile file = requestData.getFile();
        Double[] data = extractFeature(file);
        Person person = new Person().setFeature(data);
        return algService.matchPerson(person, requestData.getPoolId());
    }

    public Double[] extractFeature(MultipartFile file) throws Exception {
        BufferedImage originalImage = ImageIO.read(file.getInputStream());
        BufferedImage jpgImage = Utils.convertImg2Jpg(originalImage);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(jpgImage, "jpg", out);
        String base64 = Base64.getEncoder().encodeToString(out.toByteArray());

        Map<String, Object> options = new HashMap<>();
        options.put("vendor", "vion");
        options.put("needFaceCheck", 1);
        options.put("vendor", "vion");
        CompletableFuture<JSONObject> responseFuture = algApiClientFeature.getFeatureAndAttr(base64,
                AlgApiClient.IMAGE_TYPE_FACE, AlgApiClient.IMAGE_FORMAT_JPG, null, options);
        JSONObject jsonObject = responseFuture.get(120, TimeUnit.SECONDS);
        int success = jsonObject.getInt("success");

        if (0 == success) {
            throw new RuntimeException(jsonObject.getString("description"));
        }
        JSONObject faceFeatureJson = jsonObject.getJSONObject("faceFeature");
        String message = LocalMessageUtil.getMessage("Message.picError");
        if (faceFeatureJson == null) {
            throw new Exception("无法提取特征");
        }
        JSONArray feature = faceFeatureJson.getJSONArray("feature");
        List<Object> objects = feature.toList();

        return objects.toArray(new Double[]{});
    }

}