<?php
/*
==============================智能人像分割（抠图）接口 人像抠图返回alpha通道==============================
*/

$api_url = "https://matting.market.alicloudapi.com/segment/alpha";
$appcode = "您的appcode"; # appcode获取方式参考：https://help.aliyun.com/document_detail/157953.html

function http_call($url, $body, $appcode)
{
    $method = "POST";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    # 根据API的要求，定义相对应的Content-Type
    array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
    # 一定要在headers中加入Content-MD5头信息
    $content_md5 = base64_encode(md5($body, true));
    array_push($headers, "Content-MD5".":".$content_md5);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);

    $response = curl_exec($curl);
    $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $resp_body = substr($response, $header_size);
    if ($status_code != 200) {
        $resp_headers = substr($response, 0, $header_size);
        $resp_headers = explode("\r\n", $resp_headers);
        foreach ($resp_headers as $header) {
            if (stripos($header, "X-Ca-Error-Message") === 0) {
                print("ali api gateway return error:\n    ".$header."\n");
                return false;
            }
        }
        if ($resp_body) {
            print("server return error:\n    ".$resp_body."\n");
        }
        return false;
    }

    curl_close($curl);
    return json_decode($resp_body, true);
}

function idphoto_detect_api($photo_path)
{
    global $api_url, $appcode;;

    $file_content = file_get_contents($photo_path);

    $param = ["photo" => base64_encode($file_content),
        "type" => "jpg", # 图片类型，目前支持"jpg"和"png"两种类型
    ];
    $body = json_encode($param);

    $result = http_call($api_url, $body, $appcode);
    if ($result == false) {
        return false;
    }
    $data = $result["data"];
    var_dump($data);
    return true;
}


$photo_file = "1.jpg";

idphoto_detect_api($photo_file);
