注意事项

  • 接口返回的链接有效期为 1 小时,请及时下载存储。

消耗规则

  • 普通证件照制作:每次消耗 6算粒
  • 换装证件照制作(使用 clothes_id 参数):每次消耗 15算粒
  • 使用美颜功能auto_brightauto_smoothauto_thin_faceauto_sharp 任一启用):额外 +8算粒
  • 使用排版功能layout=1):额外 +5算粒
  • 带水印预览preview=1):不消耗算粒

图片格式要求

格式分辨率大小
jpg, jpeg, bmp, png, webp, tiff, bitmap最大 4096x4096最大15MB

快速开始


不同调用方式的区别&优缺点?
#Create a  task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=0' \
-F 'image_url=YOU_IMG_URL'

#Get the cutout result
#Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 30 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/{task_id}' \
-H 'X-API-KEY: YOUR_API_KEY' \
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "X-API-KEY: YOUR_API_KEY",
    "Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0, 'image_url' => "YOUR_IMG_URL"));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
    // request failed, log the details
    var_dump($result);
    die("post request failed");
}
//  var_dump($result);
$task_id = $result["data"]["task_id"];


//get the task result
// 1、"The polling interval is set to 1 second."
//2 "The polling time is around 30 seconds."
for ($i = 1; $i <= 30; $i++) {
    if ($i != 1) {
        sleep(1);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/".$task_id);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "X-API-KEY: YOUR_API_KEY",

    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($curl);
    $result = curl_errno($curl) ? curl_error($curl) : $response;
    curl_close($curl);
    var_dump($result);
    $result = json_decode($result, true);
    if ( !isset($result["status"]) || $result["status"] != 200 ) {
        // Task exception, logging the error.
        //You can choose to continue the loop with 'continue' or break the loop with 'break'
        var_dump($result);
        continue;
    }
    if ( $result["data"]["state"] == 1 ) {
        // task success
        var_dump($result["data"]["image"]);
        break;
    } else if ( $result["data"]["state"] < 0) {
        // request failed, log the details
        var_dump($result);
        break;
    } else {
        // Task processing
        if ($i == 30) {
            //Task processing, abnormal situation, seeking assistance from customer service of picwish
        }
    }
}

 public static void main(String[] args) throws Exception {
    String taskId = createTask();
    String result = pollingTaskResult(taskId, 0);
    System.out.println(result);
}

private static String createTask() throws Exception {
    OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
                .addFormDataPart("image_url", "IMAGE_HTTP_URL")
            .addFormDataPart("sync", "0")
            .build();
    Request request = new Request.Builder()
            .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto")
            .addHeader("X-API-KEY", "YOUR_API_KEY")
            .post(requestBody)
            .build();
    Response response = okHttpClient.newCall(request).execute();
    JSONObject jsonObject = new JSONObject(response.body().string());
    int status = jsonObject.optInt("status");
    if (status != 200) {
        throw new Exception(jsonObject.optString("message"));
    }
    return jsonObject.getJSONObject("data").optString("task_id");
}

private static String pollingTaskResult(String taskId, int pollingTime) throws Exception {
    if (pollingTime >= 30) throw new IllegalStateException("Polling result timeout.");
    OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    Request taskRequest = new Request.Builder()
            .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/" + taskId)
            .addHeader("X-API-KEY", "YOUR_API_KEY")
            .get()
            .build();
    Response taskResponse = okHttpClient.newCall(taskRequest).execute();
    JSONObject jsonObject = new JSONObject(taskResponse.body().string());
    int state = jsonObject.getJSONObject("data").optInt("state");
    if (state < 0) { // Error.
        throw new Exception(jsonObject.optString("message"));
    }
    if (state == 1) { // Success and get result.
        return jsonObject.getJSONObject("data").toString();
    }
    Thread.sleep(1000);
    return pollingTaskResult(taskId, ++pollingTime);
}
const request = require("request");
const fs = require("fs");
const path = require('path')

const API_KEY = "YOUR_API_KEY";

(async function main() {
  const taskId = await createTask()
  const result = await polling(() => getTaskResult(taskId))
  console.log(`result: ${JSON.stringify(result, null, 2)}`)
})()


const polling = async (fn, delay = 1 * 1000, timeout = 30 * 1000) => {
  if (!fn) {
    throw new Error('fn is required')
  }
  try {
    const result = await fn()
    return result
  } catch (error) {
    if (error && 'data' in error) {
      throw new Error(JSON.stringify(error, null, 2))
    }
    if (timeout <= 0) {
      throw new Error('timeout')
    }
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve()
      }, delay)
    })
    return polling(fn, delay, timeout - delay)
  }
}

function createTask() {
  return new Promise((resolve, reject) => {
    request(
      {
        method: "POST",
        url: "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto",
        headers: {
          "X-API-KEY": API_KEY,
        },
        formData: {
          image_url: 'IMAGE_HTTP_URL',
        },
        json: true
      },
      function (error, response) {
        if (response.body.data) {
          resolve(response.body.data.task_id)
        } else {
          reject(response.body)
        }
      }
    );
  })
}

function getTaskResult(taskId) {
   return new Promise((resolve, reject) => {
    request(
      {
        method: "GET",
        url: `https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/${taskId}`,
        headers: {
          "X-API-KEY": API_KEY,
        },
        json: true
      },
      function (error, response) {
        if (!response.body.data) reject(response.body)
        const { progress, state } = response.body.data
        if (state < 0) reject(response.body)
        if (progress >= 100) resolve(response.body)
        reject(null)
      }
    );
   })
}
import time
import requests

API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'

def create_task():
    headers = {'X-API-KEY': API_KEY}
    data = {'sync': '0', 'image_url': IMAGE_NETWORK_URL}
    url = 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto'

    # Create a task
    response = requests.post(url, headers=headers, data=data)

    task_id = None
    response_json = response.json()
    if 'status' in response_json and response_json['status'] == 200:
        result_tag = 'failed'
        if 'data' in response_json:
            response_json_data = response_json['data']
            if 'task_id' in response_json_data:
                result_tag = 'successful'
                task_id = response_json_data['task_id']
        print(f'Result of created task({result_tag}): {response_json}')
    else:
        # request failed, log the details
        print(f'Error: Failed to create task,{response.text}')
    return task_id

# get the task result
# 1、"The polling interval is set to 1 second."
# 2、"The polling time is around 30 seconds."
def polling_task_result(task_id,time_out=30):
    headers = {'X-API-KEY': API_KEY}
    url = f'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/{task_id}'
    for i in range(time_out):
        if i != 0:
            time.sleep(1)
        response = requests.get(url, headers=headers)
        response_json = response.json()
        if 'status' in response_json and response_json['status'] == 200:
            if 'data' in response_json:
                response_json_data = response_json['data']
                if 'state' in response_json_data:
                    task_state = response_json_data['state']
                    if task_state == 1:
                        # task success
                        print(f'Result(successful): {response_json}')
                        break
                    elif task_state < 0:
                        # Task exception, logging the error.
                        # You can choose to continue the loop with 'continue' or break the loop with 'break'
                        print(f'Result(failed): {response_json}')
                        break
            print(f'Result(polling): {response_json}')
            if i == time_out-1:
                # Timeout, log the details, and search for support from the picwish service.
                print('Error: Timeout while polling.')
        else:
            # Task exception, logging the error.
            # You can choose to continue the loop with 'continue' or break the loop with 'break'
            print(f'Error: Failed to get the task\'s result,{response.text}')
            break

def main():
    task_id = create_task()
    if task_id is None:
        print('Error: Failed to create task,task id is None.')
        return
    polling_task_result(task_id)

if __name__ == "__main__":
    main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class Program 
{
    public static HttpClient client = new HttpClient();
    private static string API_KEY = "YOUR_API_KEY";
    private static string url = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto";
    private static string imageUrl = "IMAGE_HTTP_URL";

    static async Task Main(string[] args) 
    {
        try 
        {
            //Create a task.
            var taskId = await CreateTask();
            //Retrieve the results by looping thirty times.
            var result = await Polling(() => GetTaskResult(taskId), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30));
            Console.WriteLine($"result: {result.ToString()}");
        } 
        catch (Exception ex) 
        {
            //Request from user server failed. Please record the relevant error logs. 
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }

    static async Task<string> CreateTask()
    {
        var requestUrl = url;
        var multipartContent = new MultipartFormDataContent();
        multipartContent.Add(new StringContent(imageUrl), "image_url");
        client.DefaultRequestHeaders.Add("X-API-KEY", API_KEY);

        //User server initiates a request.
        var response = await client.PostAsync(requestUrl, multipartContent);
        var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());

        if (responseJson["data"] != null) 
        {
            return responseJson["data"]["task_id"].ToString();
        } 
        else
        {
            //Request from user server failed. Please record the relevant error logs. 
            throw new Exception(responseJson.ToString());
        }
    }

    static async Task<JObject> GetTaskResult(string taskId) 
    {
        var requestUrl = $"{url}/{taskId}";
        var response = await client.GetAsync(requestUrl);
        var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());

        if (responseJson["data"]["image"] != null || responseJson["data"]["image"]["body"] != null)
        {
            return responseJson;
        } 
        else
        {
            //Task processing
            throw new Exception(responseJson.ToString());
        }
    }
    //Polling requests using the following methods 
    //1. The polling interval is set to 1 second, 
    //2. The polling time does not exceed 30 seconds
    static async Task<JObject> Polling(Func<Task<JObject>> fn, TimeSpan delay, TimeSpan timeout) 
    {
        var endTime = DateTime.Now + timeout;
        while (DateTime.Now < endTime) 
        {
            try
            {
                return await fn();
            } 
            catch
            {
                //You can choose to continue the loop with "continue" or break the loop with "break".
                Console.WriteLine("polling...");
                //Wait for one second between each loop iteration.
                await Task.Delay(delay);
            }
        }

        //Timeout, log the details, and search for support from the picwish service.
        throw new Exception("timeout");
    }
}
import UIKit
import Alamofire

let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"

/// Begin task
func start() {
    createTask { taskId in
        // Task succeed, get result. Polling requests using the following methods 1. The polling interval is 				 set to 1 second, 2. The polling time does not exceed 30 seconds
        let startTime = CFAbsoluteTimeGetCurrent()
        getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
            print(result)
        }
    }
}

/// Create a task
func createTask(completion: @escaping (String) -> Void) {
    let url = URL(string: BASE_URL)!
    let headers: HTTPHeaders = [
        "X-API-KEY": API_KEY
    ]
        
    AF.upload(multipartFormData: { multipartFormData in
        if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
            multipartFormData.append(imageUrl, withName: "image_url", fileName: "test.jpg", mimeType: "image/jpeg")
        }
    }, to: url, method: .post, headers: headers).responseData { response in
        switch response.result {
        case .success(let value):
            if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
               let data = json["data"] as? [String: Any],
               let taskId = data["task_id"] as? String {
                completion(taskId)
            }
        case .failure(let error):
            print(error)
        }
    }
}

/// Get result
func getTaskResult(taskId: String,
                   taskStartTime: CFAbsoluteTime,
                   completion: @escaping ([String: Any]) -> Void) {
    let url = URL(string: "\(BASE_URL)/\(taskId)")!

    let headers: HTTPHeaders = [
        "X-API-KEY": API_KEY
    ]
    
    AF.request(url, method: .get, headers: headers).responseData { response in
        switch response.result {
            case .success(let value):
                print(response.debugDescription)
                guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
                      let data = json["data"] as? [String: Any],
                      let state = data["state"] as? Int else {
                    print("parse failed")
                    return
                }
                // Task failed, log the details, and exit the loop
                if state < 0 {
                    return
                }
                //  Task successful
                if state == 1 {
                    if let fileUrlStr = data["image"] as? String {
                        completion(["image": fileUrlStr])
                        return
                    }
                }
          			// Retrieve the results by looping only thirty times
                let endTime = CFAbsoluteTimeGetCurrent()
                if endTime - taskStartTime < 30 {
                    // Wait for one second between each loop iteration
                    sleep(1)
                    getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
                    return
                }
                // Timeout, log the details, and search for support from the picwish service
                print("timeout")
            case .failure(let error):
                // Request from user server failed. Please record the relevant error logs
                print(error)
        }
    }
}
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"time"
)

const (
	APIKey  = "YOUR_API_KEY"
	BaseURL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
)

// taskResponse
type taskResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId string `json:"task_id"`
	} `json:"data"`
}

type VisualColorizationResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
		Image string `json:"image"`
		ImageId string `json:"image_id"`
		ReturnType  uint    `json:"return_type"`
		Progress    uint    `json:"progress"` //不确定有没有,需要查询看看
		TimeElapsed float64 `json:"time_elapsed"`
		State       int     `json:"state"`
	} `json:"data"`
}

func createTask() (string, error) {

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	_ = writer.WriteField("image_url", "YOUR_IMG_URL")
	err := writer.Close()
	if err != nil {
		fmt.Println("Close error", err)
		return "", err
	}

	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", BaseURL, body)
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	req.Header.Set("X-API-KEY", APIKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var taskResp *taskResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return "", err
	}
	if taskResp.Status != 200 {
		// Request from user server failed. Please record the relevant error logs.
		var taskError error
		taskError = errors.New("error task id")
		return "", taskError
	}
	return taskResp.Data.TaskId, nil
}

func getTaskResult(taskId string) (*VisualColorizationResponse, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", BaseURL, taskId), nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-API-KEY", APIKey)
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		//  failed. Please record the relevant error logs.
		return nil, err
	}
	var taskResp *VisualColorizationResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return nil, err
	}
	return taskResp, err
}

func main() {
	taskId, err := createTask()
	if err != nil {
		fmt.Println("Error creating task:", err)
		return
	}

	//Retrieve the results by looping thirty times.
	for i := 0; i < 29; i++ {
		if i != 0 {
			time.Sleep(time.Second) // Wait for one second between each loop iteration.
		}
		result, err := getTaskResult(taskId)
		if err != nil {
			fmt.Println("Error getting task result:", err, taskId)
			break
		}
		if result.Status != 200 {
			// Request from user server failed. Please record the relevant error logs.
			var taskError error
			taskError = errors.New("error get task id")
			fmt.Println("result error ", result, taskError, taskId)
			//You can choose to continue polling or break, both options are acceptable.
			continue
		} else {
			if result.Data.State == 1 {
				//Complete the task and end the polling.
				fmt.Println("result", result)
				break
			} else if result.Data.State < 0 {
				// Task failed, log the details, and exit the loop.
				fmt.Println("result", result)
				break
			}
			// Other tasks in the 'state' are in progress, continue polling.
			if i == 29 {
				// Timeout, log the details, and search for support from the Zuo Tang customer service.
				fmt.Println("result", result, taskId)
			}
			
		}
	}

}

#Create a  task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=1' \
-F 'image_url=YOU_IMG_URL'
<?php

//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "X-API-KEY: YOUR_API_KEY",
    "Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 1, 'image_url' => "YOUR_IMG_URL"));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
    // request failed, log the details
   die("post request failed");
}
var_dump($result);
if ( $result["data"]["state"] == 1 ) {
    // task success
  	// var_dump($result["data"]["image"]);
    // var_dump($result["data"]["image_id"]);

} else if ( $result["data"]["state"] < 0) {
    // request failed, log the details

} else {
    //Task processing, abnormal situation, seeking assistance from customer service of picwish
}


OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("image_url", "IMAGE_HTTP_URL")
        .addFormDataPart("sync", "1")
        .build();
Request request = new Request.Builder()
        .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto")
        .addHeader("X-API-KEY", "YOUR_API_KEY")
        .post(requestBody)
        .build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");

request(
  {
    method: "POST",
    url: "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto",
    headers: {
      "X-API-KEY": "YOUR_API_KEY",
    },
    formData: {
      sync: "1",
      image_url: "IMAGE_HTTP_URL",
    },
    json: true
  },
  function (error, response) {
    if (response.body.data) {
      const { progress, state } = response.body.data
      if (progress >= 100) {
        return console.log(`result:`, response.body);
      }
    }
    throw new Error(JSON.stringify(response.body, null, 2))
  }
);
import requests

API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'

def main():
    headers = {'X-API-KEY': API_KEY}
    data = {'sync': '1', 'image_url': IMAGE_NETWORK_URL}
    url = 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto'
    
    response = requests.post(url, headers=headers, data=data)

    response_json = response.json()
    if 'status' in response_json and response_json['status'] == 200:
        result_tag = 'failed'
        if 'data' in response_json:
            response_json_data = response_json['data']
            if 'state' in response_json_data:
                task_state = response_json_data['state']
                # task success
                if task_state == 1:
                    result_tag = 'successful'
                elif task_state < 0:
                    # request failed, log the details
                    pass
                else:
                    # Task processing, abnormal situation, seeking assistance from customer service of picwish
                    pass
        print(f'Result({result_tag}): {response_json}')
    else:
        # request failed, log the details
        print(f'Error: Failed to get the result,{response.text}')

if __name__ == "__main__":
    main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        string apiKey = "YOUR_API_KEY";
        string url = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto";
        string imageUrl = "IMAGE_HTTP_URL";
        string sync = "1";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);

            using (var content = new MultipartFormDataContent())
            {
                content.Add(new StringContent(sync), "sync");
                content.Add(new StringContent(imageUrl), "image_url");
                //User server initiates a request.
                var response = await client.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
                    var progress = (int)responseData.data.progress;
                    var state = (int)responseData.data.state;

                    if (progress >= 100)
                    {
                        //Task successful. 
                        Console.WriteLine($"result: {responseContent}");
                    }
                    if (state == -1) 
                    {
                        //Task processing, abnormal situation, seeking assistance from customer service of picwish
                        Console.WriteLine($"Error: {responseContent}");
                    }
                }
                else
                {
                    //Task processing, abnormal situation, seeking assistance from customer service of picwish
                    Console.WriteLine($"Error: {responseContent}");
                }
            }
        }
        Console.ReadKey();
    }
}
import UIKit
import Alamofire

func blackWhiteColor() {
    let API_KEY = "YOUR_API_KEY"
    let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"

    let headers: HTTPHeaders = ["X-API-KEY": API_KEY]
    
    AF.upload(multipartFormData: { multipartFormData in
        if let imageUrl = "{IMAGE_NETWORK_URL}".data(using: .utf8) {
            multipartFormData.append(imageUrl, withName: "image_url")
        }
        if let data = "1".data(using: .utf8) {
            multipartFormData.append(data, withName: "sync")
        }
    }, to: url, method: .post, headers: headers).responseData { response in
        print(response.debugDescription)
        switch response.result {
        case .success(let value):
            if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
               let data = json["data"] as? [String: Any],
               let taskId = data["task_id"] as? String {
                print(taskId)
            }
        case .failure(let error):
            print(error)
        }
    }
}
package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"testing"
)

type VisualColorizationResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
		Image string `json:"image"`
		ImageId string `json:"image_id"`
		ReturnType  uint    `json:"return_type"`
		Type        string  `json:"type"`
		Progress    uint    `json:"progress"` //不确定有没有,需要查询看看
		TimeElapsed float64 `json:"time_elapsed"`
		State       int     `json:"state"`
	} `json:"data"`
}

func TestColorizationTechApi(t *testing.T) {
	url := "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)

	_ = writer.WriteField("sync", "1")
	_ = writer.WriteField("image_url", "YOUR_IMG_URL")
	err := writer.Close()
	if err != nil {
		fmt.Println("Close error", err)
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("POST", url, payload)

	if err != nil {
		fmt.Println("Close error", err)
		return
	}
	req.Header.Add("X-API-KEY", "YOUR_API_KEY")

	req.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := client.Do(req)
	if err != nil {
		fmt.Println("client query error", err)
		return
	}
	defer res.Body.Close()

	respBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("Read body error", err)
		return
	}
	var taskResp *VisualColorizationResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}

	if taskResp.Status != http.StatusOK {
		// Request from user server failed. Please record the relevant error logs.
		fmt.Println("failed to get the result", taskResp)
	} else {
		if taskResp.Data.State == 1 {
			//Task successful. Recorded in the database with task ID.
			fmt.Println("result Successfully", taskResp)
		} else {
			// Task failed. Please record the relevant error logs.
			fmt.Println("result falied", taskResp)
		}
	}
}


#Create a  task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'sync=0' \
-F 'image_url=YOU_IMG_URL'


#Curl is not suitable for writing callbacks. You need to use backend languages like Go to write callback functions to receive parameters. 
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "X-API-KEY: YOUR_API_KEY",
    "Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'callback_url' => "YOUR_URL", 'image_url' => "YOUR_IMG_URL"));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
    // request failed, log the details
    var_dump($result);
    die("post request failed");
}
//  Record the task ID and store it in the database.
$task_id = $result["data"]["task_id"];

<?php
// Callback code.
// Original JSON data.
$jsonData = '{
    "status": 200,
    "message": "success",
    "data": {
        "task_id": "13cc3f64-6753-4a59-a06d-38946bc91144",
        "image": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
        "state": 1
    }
}';

// if needed,Decode JSON data.
$data = json_decode($jsonData, true);
if ( !isset($data["status"]) || $data["status"] != 200 ) {
    // request failed, log the details
    var_dump($data);
    die("post request failed");
}

if ( $data["data"]["state"] == 1 ) {
    // task success Store the image in the database based on the taskId.
       // var_dump($result["data"]["image"]);
    // var_dump($result["data"]["image_id"]);
} else if ( $data["data"]["state"] < 0) {
    // request failed, log the details
    var_dump($data);
} else {
    //Task processing, abnormal situation, seeking assistance from customer service of picwish
}


OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("image_url", "IMAGE_HTTP_URL")
        .addFormDataPart("callback_url", "YOUR_SERVER_URL")
        .build();
Request request = new Request.Builder()
        .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto")
        .addHeader("X-API-KEY", "YOUR_API_KEY")
        .post(requestBody)
        .build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");
const fs = require("fs");
const path = require('path')

request(
  {
    method: "POST",
    url: "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto",
    headers: {
      "X-API-KEY": "YOUR_API_KEY",
    },
    formData: {
      callback_url: "YOUR_SERVER_URL",
      image_url: "IMAGE_HTTP_URL",
    },
    json: true
  },
  function (error, response) {
    if (response.body.data) {
      console.log(response.body.data)
    }
    throw new Error(JSON.stringify(response.body, null, 2))
  }
);
import requests

API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'
SERVER_URL = 'YOUR_SERVER_URL'

def main():
    headers = {'X-API-KEY': API_KEY}
    data = {'callback_url': SERVER_URL, 'image_url': IMAGE_NETWORK_URL}
    url = 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto'

    response = requests.post(url, headers=headers, data=data)

    response_json = response.json()
    if 'status' in response_json and response_json['status'] == 200:
        # Task successful. Recorded in the database with task ID. 
        print(f'Result(successful): {response_json}')
    else:
        # Request from user server failed. Please record the relevant error logs. 
        print(f'Error: Failed to get the result,{response.text}')

if __name__ == "__main__":
    main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        string apiKey = "YOUR_API_KEY";
        string url = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto";
        string imageUrl = "IMAGE_HTTP_URL";
        string callbackUrl = "YOUR_SERVER_URL";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);

            using (var content = new MultipartFormDataContent())
            {
                content.Add(new StringContent(imageUrl), "image_url");
                content.Add(new StringContent(callbackUrl), "callback_url");

                //User server initiates a request.
                var response = await client.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    //Task successful. 
                    var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
                    Console.WriteLine($"result: {responseContent}");
                }
                else
                {
                    //Task processing, abnormal situation, seeking assistance from customer service of picwish                
                    Console.WriteLine($"Error: {responseContent}");
                }
            }
        }
        Console.ReadKey();
    }
}
import UIKit
import Alamofire

func blackWhiteColor() {
    let API_KEY = "YOUR_API_KEY"
    let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
    let SERVER_URL = "YOUR_SERVER_URL"

    let headers: HTTPHeaders = ["X-API-KEY": API_KEY]
    
    AF.upload(multipartFormData: { multipartFormData in
        if let imageUrl = "{IMAGE_NETWORK_URL}".data(using: .utf8) {
            multipartFormData.append(imageUrl, withName: "image_url")
        }
        if let data = SERVER_URL.data(using: .utf8) {
            multipartFormData.append(data, withName: "callback_url")
        }
    }, to: url, method: .post, headers: headers).responseData { response in
        print(response.debugDescription)
        switch response.result {
        case .success(let value):
            if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
               let data = json["data"] as? [String: Any],
               let taskId = data["task_id"] as? String {
                print(taskId)
            }
        case .failure(let error):
            print(error)
        }
    }
}	
// File 1: User server initiates a request.
package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"testing"
)

type TaskResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
	} `json:"data"`
}

func TestSegmentationTechApi(t *testing.T) {
	url := "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)

	_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
	_ = writer.WriteField("image_url", "YOUR_IMG_URL")
	err := writer.Close()
	if err != nil {
		fmt.Println("Close error", err)
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("POST", url, payload)

	if err != nil {
		fmt.Println("Close error", err)
		return
	}
	req.Header.Add("X-API-KEY", "YOUR_API_KEY")

	req.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := client.Do(req)
	if err != nil {
		fmt.Println("client query error", err)
		return
	}
	defer res.Body.Close()

	respBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("Read body error", err)
		return
	}
	var taskResp *TaskResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}
	if taskResp.Status != http.StatusOK {
		// Request from user server failed. Please record the relevant error logs.
		fmt.Println("failed to get the result", taskResp)
	} else {
		//Task successful. Recorded in the database with task ID.
		fmt.Println("result Successfully", taskResp)
	}
}




// picwish server initiates a request to the user server, and the interface of the user server receives the parameters.
package main

import (
"encoding/json"
"fmt"
)

type VisualColorizationResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
		Image string `json:"image"`
		ImageId string `json:"image_id"`
		ReturnType  uint    `json:"return_type"`
		Type        string  `json:"type"`
		Progress    uint    `json:"progress"` //不确定有没有,需要查询看看
		TimeElapsed float64 `json:"time_elapsed"`
		State       int     `json:"state"`
	} `json:"data"`
}
func main() {
	// JSON data is passed and received here, and code modification is required.
	jsonData := `{
		"status": 200,
		"message": "Success",
		"data": {
			"task_id": "123456",
			"image": "image_data",
		}
	}`

	// Parse JSON data into VisualColorizationResponse struct
	var response VisualColorizationResponse
	err := json.Unmarshal([]byte(jsonData), &response)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}
	// Query the relevant content in the database based on the taskID and associate it with the image below.
	fmt.Println("Image:", response.Data.TaskId)

	// Print the 'image' field
	// fmt.Println("Image:", response.Data.ClothesMasks)
}

#Create a task
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=0' \
-F 'image_file=@/path/to/image.jpg'

#Get the cutout result
#Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 30 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/{task_id}' \
-H 'X-API-KEY: YOUR_API_KEY' \
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "X-API-KEY: YOUR_API_KEY",
    "Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0, 'image_file' => new CURLFILE("/path/to/image.jpg")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
    // request failed, log the details
    var_dump($result);
    die("post request failed");
}
//  var_dump($result);
$task_id = $result["data"]["task_id"];


//get the task result
// 1、"The polling interval is set to 1 second."
//2 "The polling time is around 30 seconds."
for ($i = 1; $i <= 30; $i++) {
    if ($i != 1) {
        sleep(1);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/".$task_id);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "X-API-KEY: YOUR_API_KEY",

    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($curl);
    $result = curl_errno($curl) ? curl_error($curl) : $response;
    curl_close($curl);
    var_dump($result);
    $result = json_decode($result, true);
    if ( !isset($result["status"]) || $result["status"] != 200 ) {
        // Task exception, logging the error.
        //You can choose to continue the loop with 'continue' or break the loop with 'break'
        var_dump($result);
        continue;
    }
    if ( $result["data"]["state"] == 1 ) {
        // task success
        // var_dump($result["data"]["image"]);
        break;
    } else if ( $result["data"]["state"] < 0) {
        // request failed, log the details
        var_dump($result);
        break;
    } else {
        // Task processing
        if ($i == 30) {
            //Task processing, abnormal situation, seeking assistance from customer service of picwish
        }
    }
}

public static void main(String[] args) throws Exception {
    String taskId = createTask();
    String result = pollingTaskResult(taskId, 0);
    System.out.println(result);
}

private static String createTask() throws Exception {
    OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("image_file", JPG_FILE_NAME, RequestBody.create({JPG_FILE}, MediaType.parse("image/jpeg")))
            .addFormDataPart("sync", "0")
            .build();
    Request request = new Request.Builder()
            .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto")
            .addHeader("X-API-KEY", "YOUR_API_KEY")
            .post(requestBody)
            .build();
    Response response = okHttpClient.newCall(request).execute();
    JSONObject jsonObject = new JSONObject(response.body().string());
    int status = jsonObject.optInt("status");
    if (status != 200) {
        throw new Exception(jsonObject.optString("message"));
    }
    return jsonObject.getJSONObject("data").optString("task_id");
}

private static String pollingTaskResult(String taskId, int pollingTime) throws Exception {
    if (pollingTime >= 30) throw new IllegalStateException("Polling result timeout.");
    OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    Request taskRequest = new Request.Builder()
            .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/" + taskId)
            .addHeader("X-API-KEY", "YOUR_API_KEY")
            .get()
            .build();
    Response taskResponse = okHttpClient.newCall(taskRequest).execute();
    JSONObject jsonObject = new JSONObject(taskResponse.body().string());
    int state = jsonObject.getJSONObject("data").optInt("state");
    if (state < 0) { // Error.
        throw new Exception(jsonObject.optString("message"));
    }
    if (state == 1) { // Success and get result.
        return jsonObject.getJSONObject("data").toString();
    }
    Thread.sleep(1000);
    return pollingTaskResult(taskId, ++pollingTime);
}
const request = require("request");
const fs = require("fs");
const path = require('path')

const API_KEY = "YOUR_API_KEY";

(async function main() {
  const taskId = await createTask()
  const result = await polling(() => getTaskResult(taskId))
  console.log(`result: ${JSON.stringify(result, null, 2)}`)
})()


const polling = async (fn, delay = 1 * 1000, timeout = 30 * 1000) => {
  if (!fn) {
    throw new Error('fn is required')
  }
  try {
    const result = await fn()
    return result
  } catch (error) {
    if (error && 'data' in error) {
      throw new Error(JSON.stringify(error, null, 2))
    }
    if (timeout <= 0) {
      throw new Error('timeout')
    }
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve()
      }, delay)
    })
    return polling(fn, delay, timeout - delay)
  }
}

function createTask() {
  return new Promise((resolve, reject) => {
    request(
      {
        method: "POST",
        url: "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto",
        headers: {
          "X-API-KEY": API_KEY,
        },
        formData: {
          image_file: fs.createReadStream(path.join(__dirname, './test.jpg')),
        },
        json: true
      },
      function (error, response) {
        if (response.body.data) {
          resolve(response.body.data.task_id)
        } else {
          reject(response.body)
        }
      }
    );
  })
}

function getTaskResult(taskId) {
   return new Promise((resolve, reject) => {
    request(
      {
        method: "GET",
        url: `https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/${taskId}`,
        headers: {
          "X-API-KEY": API_KEY,
        },
        json: true
      },
      function (error, response) {
        if (!response.body.data) reject(response.body)
        const { progress, state } = response.body.data
        if (state < 0) reject(response.body)
        if (progress >= 100) resolve(response.body)
        reject(null)
      }
    );
   })
}
import os
import time
import requests

API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'

def create_task():
    assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'

    headers = {'X-API-KEY': API_KEY}
    data = {'sync': '0'}
    files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
    url = 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto'

    # Create a task
    response = requests.post(url, headers=headers, data=data, files=files)

    task_id = None
    response_json = response.json()
    if 'status' in response_json and response_json['status'] == 200:
        result_tag = 'failed'
        if 'data' in response_json:
            response_json_data = response_json['data']
            if 'task_id' in response_json_data:
                result_tag = 'successful'
                task_id = response_json_data['task_id']
        print(f'Result of created task({result_tag}): {response_json}')
    else:
        # request failed, log the details
        print(f'Error: Failed to create task,{response.text}')
    return task_id

# get the task result
# 1、"The polling interval is set to 1 second."
# 2、"The polling time is around 30 seconds."
def polling_task_result(task_id,time_out=30):
    headers = {'X-API-KEY': API_KEY}
    url = f'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/{task_id}'
    for i in range(time_out):
        if i != 0:
            time.sleep(1)
        response = requests.get(url, headers=headers)
        response_json = response.json()
        if 'status' in response_json and response_json['status'] == 200:
            if 'data' in response_json:
                response_json_data = response_json['data']
                if 'state' in response_json_data:
                    task_state = response_json_data['state']
                    if task_state == 1:
                        # task success
                        print(f'Result(successful): {response_json}')
                        break
                    elif task_state < 0:
                        # Task exception, logging the error.
                        # You can choose to continue the loop with 'continue' or break the loop with 'break'
                        print(f'Result(failed): {response_json}')
                        break
            print(f'Result(polling): {response_json}')
            if i == time_out-1:
                # Timeout, log the details, and search for support from the picwish service.
                print('Error: Timeout while polling.')
        else:
            # Task exception, logging the error.
            # You can choose to continue the loop with 'continue' or break the loop with 'break'
            print(f'Error: Failed to get the task\'s result,{response.text}')
            break

def main():
    task_id = create_task()
    if task_id is None:
        print('Error: Failed to create task,task id is None.')
        return
    polling_task_result(task_id)

if __name__ == "__main__":
    main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class Program
{
    public static HttpClient client = new HttpClient();
    private static string url = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto";
    private static string API_KEY = "YOUR_API_KEY";
    private static string imagePath = "test.jpg";

    static async Task Main(string[] args)
    {
        try
        {
            var taskId = await CreateTask();
            var result = await Polling(() => GetTaskResult(taskId), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30));
            Console.WriteLine($"result: {result.ToString()}");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }

    static async Task<string> CreateTask()
    {
        var requestUrl = url;
        var multipartContent = new MultipartFormDataContent();
        var fileStream = File.OpenRead(imagePath);
        multipartContent.Add(new StreamContent(fileStream), "image_file", Path.GetFileName(imagePath));
        client.DefaultRequestHeaders.Add("X-API-KEY", API_KEY);

        //User server initiates a request.
        var response = await client.PostAsync(requestUrl, multipartContent);
        var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());

        if (responseJson["data"] != null)
        {
            return responseJson["data"]["task_id"].ToString();
        }
        else
        {
            //Request from user server failed. Please record the relevant error logs. 
            throw new Exception(responseJson.ToString());
        }
    }

    static async Task<JObject> GetTaskResult(string taskId)
    {
        var requestUrl = $"{url}/{taskId}";
        var response = await client.GetAsync(requestUrl);
        var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
        // 
        if (responseJson["data"]["image"] != null || responseJson["data"]["image"]["body"] != null)
        {
            return responseJson;
        }
        else
        {
            //Task processing
            throw new Exception(responseJson.ToString());
        }
    }
    //Polling requests using the following methods 
    //1. The polling interval is set to 1 second, 
    //2. The polling time does not exceed 30 seconds
    static async Task<JObject> Polling(Func<Task<JObject>> fn, TimeSpan delay, TimeSpan timeout)
    {
        var endTime = DateTime.Now + timeout;
        while (DateTime.Now < endTime)
        {
            try
            {
                return await fn();
            }
            catch
            {
                //You can choose to continue the loop with "continue" or break the loop with "break".
                Console.WriteLine("polling...");
                //Wait for one second between each loop iteration.
                await Task.Delay(delay);
            }
        }

        //Timeout, log the details, and search for support from the picwish service.
        throw new Exception("timeout");
    }
}
import UIKit
import Alamofire

let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"

/// Begin task
func start() {
    createTask { taskId in
        // Task succeed, get result. Polling requests using the following methods 1. The polling interval is 				 set to 1 second, 2. The polling time does not exceed 30 seconds
        let startTime = CFAbsoluteTimeGetCurrent()
        getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
            print(result)
        }
    }
}

/// Create a task
func createTask(completion: @escaping (String) -> Void) {
    let url = URL(string: BASE_URL)!
    let headers: HTTPHeaders = [
        "X-API-KEY": API_KEY
    ]
    
    let imagePath = Bundle.main.path(forResource: "test", ofType: "jpg")!
    
    AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(URL(fileURLWithPath: imagePath), withName: "file", fileName: "test.jpg", mimeType: "image/jpeg")
    }, to: url, method: .post, headers: headers).responseData { response in
        switch response.result {
        case .success(let value):
            if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
               let data = json["data"] as? [String: Any],
               let taskId = data["task_id"] as? String {
                completion(taskId)
            }
        case .failure(let error):
            print(error)
        }
    }
}

/// Get result
func getTaskResult(taskId: String,
                   taskStartTime: CFAbsoluteTime,
                   completion: @escaping ([String: Any]) -> Void) {
    let url = URL(string: "\(BASE_URL)/\(taskId)")!

    let headers: HTTPHeaders = [
        "X-API-KEY": API_KEY
    ]
    
    AF.request(url, method: .get, headers: headers).responseData { response in
        switch response.result {
            case .success(let value):
                print(response.debugDescription)
                guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
                      let data = json["data"] as? [String: Any],
                      let state = data["state"] as? Int else {
                    print("parse failed")
                    return
                }
                // Task failed, log the details, and exit the loop
                if state < 0 {
                    return
                }
                //  Task successful
                if state == 1 {
                    if let fileUrlStr = data["image"] as? String {
                        completion(["image": fileUrlStr])
                        return
                    }
                }
          			// Retrieve the results by looping only thirty times
                let endTime = CFAbsoluteTimeGetCurrent()
                if endTime - taskStartTime < 30 {
                    // Wait for one second between each loop iteration
                    sleep(1)
                    getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
                    return
                }
                // Timeout, log the details, and search for support from the picwish service
                print("timeout")
            case .failure(let error):
                // Request from user server failed. Please record the relevant error logs
                print(error)
        }
    }
}
package main

import (
	"bytes"
	"encoding/json"
	_ "encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

const (
	APIKey  = "YOUR_API_KEY"
	BaseURL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
)

// taskResponse
type taskResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId string `json:"task_id"`
	} `json:"data"`
}

type VisualColorizationResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
		Image string `json:"image"`
		ImageId string `json:"image_id"`
		ReturnType  uint    `json:"return_type"`
		Progress    uint    `json:"progress"` //不确定有没有,需要查询看看
		TimeElapsed float64 `json:"time_elapsed"`
		State       int     `json:"state"`
	} `json:"data"`
}

func createTask() (string, error) {
	file, err := os.Open("test.jpg")
	if err != nil {
		return "", err
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("image_file", filepath.Base("test.jpg"))
	if err != nil {
		return "", err
	}
	_, err = io.Copy(part, file)

	err = writer.Close()
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", BaseURL, body)
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	req.Header.Set("X-API-KEY", APIKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var taskResp *taskResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return "", err
	}
	if err != nil {
		return "", err
	}
	if taskResp.Status != 200 {
		// Request from user server failed. Please record the relevant error logs.
		var taskError error
		taskError = errors.New("error task id")
		return "", taskError
	}
	return taskResp.Data.TaskId, nil
}

func getTaskResult(taskId string) (*VisualColorizationResponse, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", BaseURL, taskId), nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-API-KEY", APIKey)
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		//  failed. Please record the relevant error logs.
		return nil, err
	}
	var taskResp *VisualColorizationResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return taskResp, err
}

func main() {
	taskId, err := createTask()
	if err != nil {
		fmt.Println("Error creating task:", err)
		return
	}

	//Retrieve the results by looping thirty times.

	for i := 0; i < 30; i++ {
		if i != 0 {
			time.Sleep(time.Second) // Wait for one second between each loop iteration.
		}
		result, err := getTaskResult(taskId)
		if err != nil {
			fmt.Println("Error getting task result:", err, taskId)
			break
		}
		if result.Status != 200 {
			// Request from user server failed. Please record the relevant error logs.
			var taskError error
			taskError = errors.New("error get task id")
			fmt.Println("result error ", result, taskError, taskId)
			//You can choose to continue polling or break, both options are acceptable.
			continue
		} else {
			if result.Data.State == 1 {
				//Complete the task and end the polling.
				fmt.Println("result", result)
				break
			} else if result.Data.State < 0 {
				// Task failed, log the details, and exit the loop.
				fmt.Println("result", result)
				break
			}
			// Other tasks in the 'state' are in progress, continue polling.
			if i == 29 {
				// Timeout, log the details, and search for support from the Zuo Tang customer service.
				fmt.Println("result", result, taskId)
			}
			
		}
	}

}

#Create a  task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=1' \
-F 'image_file=@/path/to/image.jpg'
<?php

//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "X-API-KEY: YOUR_API_KEY",
    "Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 1, 'image_file' => new CURLFILE("/path/to/image.jpg")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
    // request failed, log the details
    var_dump($result);
    die("post request failed");
}
var_dump($result);
if ( $result["data"]["state"] == 1 ) {
    // task success 
    // var_dump($result["data"]["image"]);
    // var_dump($result["data"]["image_id"]);

} else if ( $result["data"]["state"] < 0) {
    // request failed, log the details

} else {
    //Task processing, abnormal situation, seeking assistance from customer service of picwish
}


OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("image_file", JPG_FILE_NAME, RequestBody.create({JPG_FILE}, MediaType.parse("image/jpeg")))
        .addFormDataPart("sync", "1")
        .build();
Request request = new Request.Builder()
        .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto")
        .addHeader("X-API-KEY", "YOUR_API_KEY")
        .post(requestBody)
        .build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");
const fs = require("fs");
const path = require('path')

request(
  {
    method: "POST",
    url: "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto",
    headers: {
      "X-API-KEY": "YOUR_API_KEY",
    },
    formData: {
      sync: "1",
      image_file: fs.createReadStream(path.join(__dirname, './test.jpg')),
    },
    json: true
  },
  function (error, response) {
    if (response.body.data) {
      const { progress, state } = response.body.data
      if (progress >= 100) {
        return console.log(`result:`, response.body);
      }
    }
    throw new Error(JSON.stringify(response.body, null, 2))
  }
);
import os
import requests

API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'

def main():
    assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'

    headers = {'X-API-KEY': API_KEY}
    data = {'sync': '1'}
    files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
    url = 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto'

    # Create a task
    response = requests.post(url, headers=headers, data=data, files=files)

    response_json = response.json()
    if 'status' in response_json and response_json['status'] == 200:
        result_tag = 'failed'
        if 'data' in response_json:
            response_json_data = response_json['data']
            if 'state' in response_json_data:
                task_state = response_json_data['state']
                # task success
                if task_state == 1:
                    result_tag = 'successful'
                elif task_state < 0:
                    # request failed, log the details
                    pass
                else:
                    # Task processing, abnormal situation, seeking assistance from customer service of picwish
                    pass
        print(f'Result({result_tag}): {response_json}')
    else:
        # request failed, log the details
        print(f'Error: Failed to get the result,{response.text}')

if __name__ == "__main__":
    main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        string apiKey = "YOUR_API_KEY";
        string url = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto";
        string imagePath = "test.jpg";
        string sync = "1";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);

            using (var content = new MultipartFormDataContent())
            {
                var imageContent = new StreamContent(File.OpenRead(imagePath));
                imageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");

                content.Add(new StringContent(sync), "sync");
                content.Add(imageContent, "image_file", Path.GetFileName(imagePath));
                //User server initiates a request.
                var response = await client.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
                    var progress = (int)responseData.data.progress;
                    var state = (int)responseData.data.state;

                    if (progress >= 100)
                    {
                        //Task successful.
                        Console.WriteLine($"result: {responseContent}");
                    }
                    if (state == -1) 
                    {
                        //Task processing, abnormal situation, seeking assistance from customer service of picwish
                        Console.WriteLine($"Error: {responseContent}");
                    }
                }
                else
                {
                    //Task processing, abnormal situation, seeking assistance from customer service of picwish
                    Console.WriteLine($"Error: {responseContent}");
                }
            }
        }
        Console.ReadKey();
    }
}
import UIKit
import Alamofire

func blackWhiteColor() {
    let API_KEY = "YOUR_API_KEY"
    let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"

    let url = URL(string: BASE_URL)!
    let image = UIImage(named: "blackWhite.jpg")!
    let fileUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("blackWhite.jpg")
    let imageData = image.jpegData(compressionQuality: 0.9)!
    try? imageData.write(to: fileUrl)

    let headers: HTTPHeaders = ["X-API-KEY": API_KEY]
    
    AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(fileUrl, withName: "image_file", fileName: "blackWhite.jpg", mimeType: "image/jpeg")
        if let data = "1".data(using: .utf8) {
            multipartFormData.append(data, withName: "sync")
        }
    }, to: url, method: .post, headers: headers).responseData { response in
        print(response.debugDescription)
        switch response.result {
        case .success(let value):
            if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
               let data = json["data"] as? [String: Any],
               let taskId = data["task_id"] as? String {
                print(taskId)
            }
        case .failure(let error):
            print(error)
        }
    }
}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
)

type VisualColorizationResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
		Image string `json:"image"`
		ImageId string `json:"image_id"`
		ReturnType  uint    `json:"return_type"`
		Progress    uint    `json:"progress"` //不确定有没有,需要查询看看
		TimeElapsed float64 `json:"time_elapsed"`
		State       int     `json:"state"`
	} `json:"data"`
}

func main() {
	apiKey := "YOUR_API_KEY"
	url := "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
	imagePath := "test.jpg"

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	_ = writer.WriteField("sync", "1")

	file, err := os.Open(imagePath)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}
	defer file.Close()

	part, err := writer.CreateFormFile("image_file", filepath.Base(imagePath))
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}

	io.Copy(part, file)

	writer.Close()

	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}

	req.Header.Set("X-API-KEY", apiKey)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}
	defer res.Body.Close()

	respBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("Error: ", err)

		return
	}
	var taskResp VisualColorizationResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}
	if taskResp.Status != http.StatusOK {
		// Request from user server failed. Please record the relevant error logs.
		fmt.Println("failed to get the result", taskResp)
	} else {
		if taskResp.Data.State == 1 {
			//Task successful. Recorded in the database with task ID.
			fmt.Println("result Successfully", taskResp)
		} else {
			// Task failed. Please record the relevant error logs.
			fmt.Println("result falied", taskResp)
		}
	}
}

#Create a  task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'image_file=@/path/to/image.jpg'

#Curl is not suitable for writing callbacks. You need to use backend languages like Go to write callback functions to receive parameters. 
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "X-API-KEY: YOUR_API_KEY",
    "Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'callback_url' => "YOUR_SERVER_URL", 'image_file' => new CURLFILE("/path/to/image.jpg")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
    // request failed, log the details
    var_dump($result);
    die("post request failed");
}
//  Record the task ID and store it in the database.
$task_id = $result["data"]["task_id"];

<?php
// Callback code.
// Original JSON data.
$jsonData = '{
    "status": 200,
    "message": "success",
    "data": {
        "task_id": "13cc3f64-6753-4a59-a06d-38946bc91144",
        "image": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
        "state": 1
    }
}';

// if needed,Decode JSON data.
$data = json_decode($jsonData, true);
if ( !isset($data["status"]) || $data["status"] != 200 ) {
    // request failed, log the details
    var_dump($data);
    die("post request failed");
}

if ( $data["data"]["state"] == 1 ) {
    // task success Store the image in the database based on the taskId.
      // var_dump($result["data"]["image"]);
    // var_dump($result["data"]["image_id"]);
} else if ( $data["data"]["state"] < 0) {
    // request failed, log the details
    var_dump($data);
} else {
    //Task processing, abnormal situation, seeking assistance from customer service of picwish
}

OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("image_file", JPG_FILE_NAME, RequestBody.create({JPG_FILE}, MediaType.parse("image/jpeg")))
        .addFormDataPart("callback_url", "YOUR_SERVER_URL")
        .build();
Request request = new Request.Builder()
        .url("https://techsz.aoscdn.com/api/tasks/visual/external/idphoto")
        .addHeader("X-API-KEY", "YOUR_API_KEY")
        .post(requestBody)
        .build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");
const fs = require("fs");
const path = require('path')

request(
  {
    method: "POST",
    url: "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto",
    headers: {
      "X-API-KEY": "YOUR_API_KEY",
    },
    formData: {
      callback_url: "YOUR_SERVER_URL",
      image_file: fs.createReadStream(path.join(__dirname, './test.jpg')),
    },
    json: true
  },
  function (error, response) {
    if (response.body.data) {
      console.log(response.body.data)
    }
    throw new Error(JSON.stringify(response.body, null, 2))
  }
);
import os
import requests

API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'
SERVER_URL = 'YOUR_SERVER_URL'

def main():
    assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'

    headers = {'X-API-KEY': API_KEY}
    data = {'callback_url': SERVER_URL}
    files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
    url = 'https://techsz.aoscdn.com/api/tasks/visual/external/idphoto'

    # Create a task
    response = requests.post(url, headers=headers, data=data, files=files)

    response_json = response.json()
    if 'status' in response_json and response_json['status'] == 200:
        # Task successful. Recorded in the database with task ID. 
        print(f'Result(successful): {response_json}')
    else:
        # Request from user server failed. Please record the relevant error logs. 
        print(f'Error: Failed to get the result,{response.text}')

if __name__ == "__main__":
    main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        string apiKey = "YOUR_API_KEY";
        string url = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto";
        string imagePath = "test.jpg";
        string callbackUrl = "YOUR_SERVER_URL";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);

            using (var content = new MultipartFormDataContent())
            {
                var imageContent = new StreamContent(File.OpenRead(imagePath));
                imageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");

                content.Add(new StringContent(callbackUrl), "callback_url");
                content.Add(imageContent, "image_file", Path.GetFileName(imagePath));
                //User server initiates a request.
                var response = await client.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {   
                    //Task successful. 
                    var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
                    Console.WriteLine($"result: {responseContent}");
                }
                else
                {
                    //Task processing, abnormal situation, seeking assistance from customer service of picwish
                    Console.WriteLine($"Error: {responseContent}");
                }
            }
        }
        Console.ReadKey();
    }
}
import UIKit
import Alamofire

func blackWhiteColor() {
    let API_KEY = "YOUR_API_KEY"
    let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
    let SERVER_URL = "YOUR_SERVER_URL"

    let url = URL(string: BASE_URL)!
    let image = UIImage(named: "blackWhite.jpg")!
    let fileUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("blackWhite.jpg")
    let imageData = image.jpegData(compressionQuality: 0.9)!
    try? imageData.write(to: fileUrl)

    let headers: HTTPHeaders = ["X-API-KEY": API_KEY]
    
    AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(fileUrl, withName: "image_file", fileName: "blackWhite.jpg", mimeType: "image/jpeg")
        if let data = SERVER_URL.data(using: .utf8) {
            multipartFormData.append(data, withName: "callback_url")
        }
    }, to: url, method: .post, headers: headers).responseData { response in
        print(response.debugDescription)
        switch response.result {
        case .success(let value):
            if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
               let data = json["data"] as? [String: Any],
               let taskId = data["task_id"] as? String {
                print(taskId)
            }
        case .failure(let error):
            print(error)
        }
    }
}
// File 1: User server initiates a request.
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
)

type TaskResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
	} `json:"data"`
}

func main() {
	apiKey := "YOUR_API_KEY"
	url := "https://techsz.aoscdn.com/api/tasks/visual/external/idphoto"
	imagePath := "test.jpg"

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")

	file, err := os.Open(imagePath)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}
	defer file.Close()

	part, err := writer.CreateFormFile("image_file", filepath.Base(imagePath))
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}

	io.Copy(part, file)

	writer.Close()

	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}

	req.Header.Set("X-API-KEY", apiKey)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}
	defer res.Body.Close()

	respBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("Error: ", err)

		return
	}
	var taskResp TaskResponse
	err = json.Unmarshal(respBody, &taskResp)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}
	if taskResp.Status != http.StatusOK {
		// Request from user server failed. Please record the relevant error logs.
		fmt.Println("failed to get the result", taskResp)
	} else {
		//Task successful. Recorded in the database with task ID.
		fmt.Println("failed to get the result", taskResp)
	}
}




// picwish server initiates a request to the user server, and the interface of the user server receives the parameters.
package main

import (
"encoding/json"
"fmt"
)

type VisualColorizationResponse struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
	Data    struct {
		TaskId      string  `json:"task_id"`
		Image string `json:"image"`
		ImageId string `json:"image_id"`
		ReturnType  uint    `json:"return_type"`
		Type        string  `json:"type"`
		Progress    uint    `json:"progress"` //不确定有没有,需要查询看看
		TimeElapsed float64 `json:"time_elapsed"`
		State       int     `json:"state"`
	} `json:"data"`
}

func main() {
	// JSON data is passed and received here, and code modification is required.
	jsonData := `{
		"status": 200,
		"message": "Success",
		"data": {
			"task_id": "123456",
			"image": "image_data",
		}
	}`

	// Parse JSON data into VisualColorizationResponse struct
	var response VisualColorizationResponse
	err := json.Unmarshal([]byte(jsonData), &response)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}
	// Query the relevant content in the database based on the taskID and associate it with the image below.
	fmt.Println("Image:", response.Data.TaskId)

	// Print the 'image' field
	// fmt.Println("Image:", response.Data.ClassMasks)
	// fmt.Println("Image:", response.Data.ClothesMasks)
}

请求说明

  • 创建证件照任务

  • 请求 URL: https://techsz.aoscdn.com/api/tasks/visual/external/idphoto

  • HTTP 方法: POST

a. 头部信息(Header)

参数名称参数类型说明
X-API-KEYstring您的专属 API Key

请求参数

参数 类型 必填 说明 备注
基础参数
image_file file
图片文件
支持jpg, jpeg, bmp, png, webp, tiff, bitmap。二者必选其一,优先级 image_file>image_url。输入图片小于15MB,分辨率最大4096x4096
image_url string
图片下载地址
支持HTTP协议和OSS协议,最长512字符,下载超时10秒
last_id string
复用上次任务输入
任务返回中的image_id(不是任务id),提供则可不传图片输入
sync int
同步异步
默认值: 0
可选值: 0, 1
1=同步, 0=异步
证件照规格参数
spec_id int
规格ID
规格对应证件照的尺寸、背景色、人脸尺寸、文件大小
dpi int
分辨率dpi
默认值: 300
最小值10,最大值1000
px_width int
像素宽
可传入(px_width, px_height)或(mm_width, mm_height)中的一对值,默认(295, 413),小于1800像素
px_height int
像素高
与px_width搭配使用,小于1800像素
mm_width int
毫米宽
与mm_height搭配使用,小于180毫米
mm_height int
毫米高
与mm_width搭配使用,小于180毫米
背景色参数
change_bg int
是否抠图换背景
默认值: 1
可选值: 0, 1
0或1
bg_color string
背景色
16进制表示,常用颜色: 白色FFFFFF、红色FF0000、蓝色438EDB,默认白色
bg_color2 string
渐变背景色
16进制表示,背景色会从顶部的bg_color渐变到底部的bg_color2,默认为空
人脸尺寸约束参数
face_width int
脸宽
人脸宽度(像素)
min_face_width int
最小脸宽
最小人脸宽度(像素)
max_face_width int
最大脸宽
最大人脸宽度(像素)
face_height int
脸高
人脸长度(像素)
min_face_height int
最小脸高
最小人脸长度(像素)
max_face_height int
最大脸高
最大人脸长度(像素)
head_top int
头顶距上边
头顶与上边距离(像素)
min_head_top int
最小头顶距上边
头顶与上边最小距离(像素)
max_head_top int
最大头顶距上边
头顶与上边最大距离(像素)
chin_top int
下巴距上边
下巴与上边距离(像素)
min_chin_top int
最小下巴距上边
下巴与上边最小距离(像素)
max_chin_top int
最大下巴距上边
下巴与上边最大距离(像素)
eyes_top int
眼睛距上边
眼睛与上边距离(像素)
min_eyes_top int
最小眼睛距上边
眼睛与上边最小距离(像素)
max_eyes_top int
最大眼睛距上边
眼睛与上边最大距离(像素)
美颜参数
auto_bright int
自动提亮
默认值: 0
可选值: 0, 1
0或1,是否自动调光
bright_factor float
提亮强度
默认值: 0.5
[0, 1],调光系数
auto_smooth int
自动磨皮
默认值: 0
可选值: 0, 1
0或1,是否自动磨皮
smooth_factor float
磨皮强度
默认值: 0.5
[0, 1],磨皮系数
auto_thin_face int
自动瘦脸
默认值: 0
可选值: 0, 1
0或1,是否自动瘦脸
thin_face_factor float
瘦脸强度
默认值: 0.5
[0, 1],瘦脸系数
auto_sharp int
自动锐化
默认值: 0
可选值: 0, 1
0或1,是否自动锐化
sharp_factor float
锐化强度
默认值: 0.5
[0, 1],锐化系数
换装参数
clothes_id string 换正装, man_1~man_20, woman_1~woman_20, child_1~child_10,默认为空
预览与水印参数
preview int
是否仅预览
默认值: 0
可选值: 0, 1
0或1,预览有水印,不扣算粒
文件大小控制参数
quality int
压缩质量
默认值: 92
[1, 100],越大生成的证件照文件越大
min_file_size int
目标最小体积(Bytes)
[0, inf],比如10240表示最小文件大小为10KB,只有当quality为空时起作用,默认为空
max_file_size int
目标最大体积(Bytes)
[0, inf],只有当quality为空时起作用,默认为空
标签参数
add_label int
是否添加标签
默认值: 0
可选值: 0, 1
0或1,是否在证件照底部加标签
label_text string
标签文案
证件照底部标签内容,默认为空
label_height int
标签高度
默认值: 30
证件照底部标签高度(像素)
排版参数
layout int
是否排版
默认值: 0
可选值: 0, 1
0或1,是否返回排版
layout_vertical int
排版方向
默认值: 0
可选值: 0, 1
0或1,返回横版或竖版排版,默认为横版
layout_size string
纸张尺寸
默认值: 5inch
可选值: 5inch, 6inch
"5inch"或"6inch",排版尺寸五寸或六寸
layout_bg_color string
画布背景色
16进制表示,比如: 白色FFFFFF,默认为灰色
layout_qr_code_data string
二维码数据
排版附加二维码数据,默认为空
layout_qr_code_size int
二维码尺寸
默认值: 290
排版附加二维码尺寸像素
layout_label_text string
画布标签文案
排版附加文字,换行用\n表示,默认为空

返回示例

1. 异步模式(sync=0)

成功返回示例

{
  "status": 200,
  "message": "ok",
  "data": {
    "task_id": "94806a3f-1173-4afb-9bcc-3ff19c0981f4"
  }
}

错误返回示例

{
  "status": 401,
  "message": "Invalid API key"
}

返回字段说明

字段返回类型说明
statusint200 请求成功,非 200 请求失败,请参考 http 响应代码
messagestring返回的信息说明
dataobject-
├─ task_idstring任务 id,通过此 id 可以查询证件照结果

2. 轮询证件照结果

: 整体轮询时长不超过 5 分钟,轮询间隔推荐 1s,获取到证件照结果后或者结果异常请退出轮询。

  • 请求 URL: https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/{task_id}
  • HTTP 方法: GET

URL 参数

a. 头部信息(Header)

参数名称参数类型说明
X-API-KEYstring您的专属 API Key

b. url 地址参数

参数参数类型说明
task_idstring第一步证件照任务请求返回的 task_id

成功返回示例

处理中

{
  "status": 200,
  "message": "success",
  "data": {
    "progress": 21,
    "state": 4
  }
}

处理完成

{
  "status": 200,
  "data": {
    "completed_at": 1758771079,
    "created_at": 1758771079,
    "image": "https://wxtechdev.oss-cn-shenzhen.aliyuncs.com/tasks/output/visual_external_idphoto/90662b52-deca-42eb-99fa-141289cbd3c1.jpg",
    "image_id": "19e2bfa2-99c0-11f0-823d-a3b20139f801",
    "processed_at": 1758771079,
    "progress": 100,
    "return_type": 1,
    "state": 1,
    "state_detail": "Complete",
    "task_id": "90662b52-deca-42eb-99fa-141289cbd3c1"
  }
}

错误返回示例

请求失败

{
  "status": 401,
  "message": "Invalid API key"
}

处理失败

{
  "status": 200,
  "message": "success",
  "data": {
    "created_at": 1634884056,
    "processed_at": 1634884056,
    "progress": 0,
    "state": -1,
    "task_id": "8576761c-fbe5-48a7-9620-18f9ebb132b3"
  }
}

返回字段说明

字段返回类型说明
statusint200 请求成功,非 200 请求失败,请参考下面的 Http 响应状态码
messagestring返回的信息说明。如果证件照失败,可以参考此参数返回信息,或者携带此参数寻找相应客服人员。
dataobject-
├─ stateintstate < 0(处理失败)
• -8: 处理超时,最长处理时间 30 秒
• -7: 无效图片文件(比如图片损坏、格式不对等)
• -5: url 图片超出大小(15MB)
• -3: 传入 image,服务器下载失败(麻烦检查文件 URL 是否可用)
• -2: 证件照完成,上传 oss 失败
• -1: 证件照失败
state = 0(排队中)
state = 1(完成)
state = 2(准备中)
state = 3(等待中)
state = 4(处理中)
排队中表示任务正在队列中,等待证件照;处理中指证件照正在进行。
├─ progressint任务处理进度(百分比),取值范围:0~100。100 表示处理完成,< 100 表示正在处理中
├─ task_idstring任务 ID,如果证件照失败,请携带此参数寻找相应客服人员
├─ imagestring证件照处理的结果图片的下载地址或者 base64 数据
├─ image_idstring任务返回中的 image_id,不是任务 id,是用来下次图片复用的,也是输入中的 last_id
├─ created_atint任务创建时间戳
├─ processed_atint任务开始被处理的时间戳
├─ completed_atint任务完成时间戳
├─ time_elapsedstring耗时

证件照规格列表

spec_id 分类 标题 尺寸(mm) 尺寸(px) DPI 颜色要求
1101 通用 小一寸 22x32 260x378 300 无要求
1102 通用 一寸 25x35 295x413 300 无要求
1103 通用 大一寸 33x48 390x567 300 无要求
1104 通用 小二寸 35x45 413x531 300 无要求
1105 通用 二寸 35x49 413x579 300 无要求
1106 通用 大二寸 35x53 413x626 300 无要求
1107 通用 三寸 55x84 649x991 300 无要求
1108 通用 四寸 76x102 898x1205 300 无要求
1109 通用 五寸 89x127 1051x1500 300 无要求
2101 政府 社保卡 26x32 358x441 350 白色
2102 政府 身份证 26x32 358x441 350 白色
2103 政府 居住证 26x32 358x441 350 白色
2201 政府 健康证(一寸) 25x35 295x413 300 蓝色, 白色
2202 政府 健康证(小二寸) 35x45 413x531 300 蓝色, 白色
2203 政府 医保证 26x32 358x441 300 白色
2301 政府 驾驶证、驾照(无回执,小一寸) 22x32 260x378 300 白色
2401 政府 退役军人优待证 30x37 352x440 300 白色
3101 签证 巴西签证 40x50 472x590 300 白色
3102 签证 冰岛签证 40x50 472x590 300 白色
3103 签证 阿根廷签证 40x40 472x472 300 白色
3105 签证 韩国签证 35x45 413x531 300 白色
3106 签证 肯尼亚签证 50x50 590x590 300 白色
3107 签证 马来西亚签证 35x45 413x531 300 白色
3108 签证 美国签证 51x51 602x602 300 白色
3109 签证 日本签证 45x45 531x531 300 白色
3110 签证 世界通用签证 35x45 413x531 300 白色
3111 签证 泰国签证 35x45 413x531 300 白色
3112 签证 新西兰签证 35x45 413x531 300 白色
3113 签证 意大利签证 35x45 413x531 300 白色
3114 签证 以色列签证 51x51 602x602 300 白色
3115 签证 印度签证 51x51 602x602 300 白色
3116 签证 越南签证 35x45 413x531 300 蓝色, 红色, 白色
3117 签证 老挝签证 51x51 602x602 300 白色
3118 签证 法国签证 35x45 413x531 300 白色
3119 签证 缅甸签证 35x45 413x531 300 白色
3120 签证 加拿大签证 35x45 413x531 300 白色
3121 签证 菲律宾签证 51x51 602x602 300 白色
3202 签证 海外申请护照在线预约照片 33x48 389x566 300 白色
3301 签证 入台证 35x45 413x531 300 白色
3302 签证 港澳通行证 33x48 389x566 300 白色
4101 学生 入学照(二寸) 35x49 413x578 300 蓝色, 红色, 白色
4102 学生 入学照(一寸) 25x35 295x413 300 蓝色, 红色, 白色
4103 入学 香港学生国内报名 40x50 472x590 300 白色
4201 学生 全国中小学生学籍照片 26x32 307x378 150 白色
4301 学生 大学生图像信息采集 41x54 480x640 300 蓝色
4401 学生 毕业照 41x54 480x640 300 蓝色, 白色
5101 考试 国家公务员考试(一寸) 25x35 295x413 300 蓝色, 白色
5130 考试 国家公务员考试(小二寸) 35x45 413x531 300 蓝色, 白色
5131 考试 国家公务员考试(二寸) 35x49 413x579 300 蓝色, 白色
5102 考试 安徽公务员考试 25x35 413x531 300 蓝色, 白色
5103 考试 北京公务员考试 34x45 401x531 300 蓝色, 白色
5104 考试 成都公务员考试 9x11 102x126 300 蓝色, 白色, 红色
5132 考试 成都公务员考试 25x35 295x413 300 蓝色, 白色
5105 考试 甘肃公务员考试 35x49 413x579 300 蓝色, 白色
5106 考试 广西公务员考试 25x35 295x413 300 蓝色, 白色
5107 考试 广州公务员考试 35x49 295x413 300 蓝色, 白色
5108 考试 贵州公务员考试 18x25 215x300 300 蓝色, 白色, 红色
5109 考试 海南公务员考试 35x45 413x531 300 蓝色
5110 考试 河北公务员考试 25x35 295x413 300 蓝色, 白色, 红色
5111 考试 河南公务员考试 25x35 295x413 300 蓝色, 白色, 红色
5112 考试 黑龙江公务员考试 35x45 413x531 300 蓝色, 白色, 红色
5113 考试 湖北公务员考试 25x35 295x413 300 蓝色, 白色
5114 考试 湖南公务员考试 35x45 413x531 300 蓝色, 白色
5115 考试 江苏公务员考试 35x45 413x531 300 蓝色, 白色
5116 考试 江西公务员考试 35x45 413x531 300 蓝色, 白色
5117 考试 宁夏公务员考试 35x45 413x531 300 蓝色, 白色
5118 考试 青海公务员考试 35x45 413x531 300 蓝色, 白色
5119 考试 山东公务员考试 35x49 413x579 300 蓝色, 白色, 红色
5120 考试 山西公务员考试 25x35 295x413 300 蓝色, 白色, 红色
5121 考试 上海公务员考试 13x17 150x200 300 蓝色, 白色
5122 考试 陕西公务员考试 35x45 413x531 300 蓝色, 白色
5123 考试 深圳公务员考试 35x53 413x626 300 蓝色, 白色, 红色
5124 考试 四川公务员考试 25x35 295x413 300 蓝色, 白色
5125 考试 西藏公务员考试 25x35 295x413 300 蓝色, 白色
5126 考试 新疆公务员考试 35x45 413x531 300 蓝色, 白色
5127 考试 云南公务员考试 35x49 413x579 300 蓝色, 白色, 红色
5128 考试 山西省省直事业单位考试报名 25x35 295x413 300 白色
5129 考试 重庆公务员考试 25x35 295x413 300 蓝色, 白色
5201 考试 国考(二寸) 35x45 413x531 300 蓝色, 白色
5202 考试 国考(一寸) 25x35 295x413 300 蓝色, 白色
5203 考试 甘肃省(国考) 25x35 295x413 300 蓝色, 白色, 红色
5204 考试 江西省(国考) 35x53 413x626 300 蓝色, 白色
5205 考试 宁夏回族自治区(国考) 35x45 413x531 300 蓝色, 白色
5206 考试 青海省(国考) 35x45 413x531 300 蓝色, 白色
5207 考试 上海市(国考) 35x53 413x626 300 蓝色
5301 考试 成人高考报名 40x54 480x640 300 蓝色
5302 考试 成人自考 40x54 480x640 300 蓝色, 白色
5303 考试 成人自考 25x34 300x400 300 蓝色, 白色
5401 考试 高考报名(一寸) 25x35 295x413 300 蓝色, 白色
5402 考试 高考报名(小二寸) 35x45 413x531 300 蓝色, 白色
5403 考试 上海中考网报名 14x20 168x240 300 蓝色, 白色, 红色
5404 考试 武汉大学研究生考试 13x17 150x200 300 蓝色, 白色, 红色
5405 考试 研究生考试 33x48 390x567 300 蓝色, 白色
5406 考试 在职研究生考试 35x45 413x531 300 蓝色, 白色
5501 考试 普通话水平测试 33x48 390x567 300 蓝色, 白色, 红色
5502 考试 商务英语考试 35x49 413x579 300 蓝色, 白色
5503 考试 学位英语 33x48 390x567 300 白色
5504 考试 英语AB级考试(二寸) 33x48 390x567 300 蓝色
5505 考试 英语AB级考试(144X192) 12x16 144x192 300 蓝色, 白色
5506 考试 英语三级考试 12x16 295x413 300 蓝色
5507 考试 英语四级考试 33x43 390x507 300 蓝色, 白色
5508 考试 英语四级考试 12x16 144x192 300 蓝色, 白色
5509 考试 英语六级考试 12x16 144x192 300 蓝色, 白色
5510 考试 自考学位外语考试 40x54 480x640 300 蓝色
5601 考试 证券考试报名 18x25 215x300 300 蓝色, 白色, 红色
5602 考试 注册会计师考试(一寸) 25x35 295x413 300 白色
5603 考试 注册会计师考试(178x220) 15x19 178x220 300 白色
5701 考试 国家医学考试 25x35 295x413 300 蓝色, 白色
5702 考试 护士职业资格考试 35x45 413x531 300 白色
5703 考试 执业药师资格考试(一寸) 25x35 295x413 300 白色
5801 考试 计算机等级考试 12x16 144x192 300 白色
5802 考试 青少年电子信息等级考试 35x53 413x626 300 蓝色, 红色
5803 考试 青少年机器人技术等级考试 35x53 413x626 300 蓝色, 白色
5901 考试 BIM技能等级考试 25x35 295x413 300 白色
5902 考试 卫生专业技术资格考试(一寸) 25x35 295x413 300 白色
5903 考试 一级注册消防工程师考试 25x35 295x413 300 白色
5904 考试 育婴师考试报名(一寸) 25x35 295x413 300 白色
5905 考试 国家司法考试 35x53 413x626 300 蓝色, 白色, 红色
5906 考试 裁判资格考试 25x35 295x413 300 蓝色
6101 资质 二级建造师证(一寸) 25x35 295x413 300 蓝色, 白色
6102 资质 二级建造师证(二寸) 35x53 413x626 300 蓝色, 白色
6103 资质 一级建造师 25x35 295x413 300 白色
6201 资质 导游证(一寸) 25x35 295x413 300 白色
6202 资质 导游证(二寸) 35x53 413x626 300 白色
6302 资质 职业兽医资格证 19x28 230x334 300 蓝色, 白色
6303 资质 职业医师资格证(小二寸) 35x45 413x531 300 白色
6401 资质 教师资格证(300x400) 25x34 300x400 300 白色
6501 资质 保险职业证(210x270) 18x23 210x270 300 白色
6502 资质 会计从业资格证(一寸) 25x35 295x413 300 白色
6601 资质 执法证 40x54 480x640 300 白色