Notice
- The URL of the result image is valid for 1 hour. Please download the image file promptly.
Credit Consumption Rules
- Standard ID Photo:
6 credits
per request - ID Photo with Outfit Change (using
clothes_id
parameter):15 credits
per request - Beauty Enhancement (any of
auto_bright
,auto_smooth
,auto_thin_face
,auto_sharp
enabled):+8 credits
extra - Layout Feature (
layout=1
):+5 credits
extra - Watermarked Preview (
preview=1
):No credits consumed
Supported Images
Format | Resolution | File size |
---|---|---|
jpg, jpeg, bmp, png, webp, tiff, bitmap | Up to 4096 x 4096 | Up to 15MB |
Get Started
See differences between the 3 API call types
API Call Types | Request | Return | Pros & Cons |
---|---|---|---|
Asynchronous | After sending a request, users do not have to wait for an immediate response from the server. The user can obtain the result via Polling. | Return the result by Polling. | Pros: High success rate when concurrency is high; high processing success rate when network transmission is slow or unstable. Cons: One more interface call compared to synchronous option. |
Synchronous | Send a request and wait to obtain real-time updates from the server. | Immediately return the result. | Pros: Easy to integrate. Cons: Lower success rate when concurrency is high or network transmission is slow or unstable as compared to asynchronous option. |
Callback | After sending a request, users do not have to wait for an immediate response from the server. When the task is completed, the server will send a callback notification. | After setting the callback URL, the server sends a notification back to the user. | Pros: Highest processing success rate. Cons: The user requires a server and corresponding back-end resources. |
Asynchronous API Call Sequence Diagram

Synchronous API Call Sequence Diagram

Callback Notification Sequence Diagram

#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)
}
Request Instructions
-
Create ID Photo Task
-
Request URL:
https://techsz.aoscdn.com/api/tasks/visual/external/idphoto
-
HTTP Method: POST
a. Header Information
Parameter | Type | Description |
---|---|---|
X-API-KEY | string | Your exclusive API Key |
Request Parameters
Parameter | Type | Required | Description | Notes |
---|---|---|---|---|
Basic Parameters | ||||
image_file | file | No | Image file | Supports jpg, jpeg, bmp, png, webp, tiff, bitmap. Either image_file or image_url. Priority: image_file>image_url. Image size <15MB, max resolution 4096x4096 |
image_url | string | No | Image download URL | Supports HTTP and OSS protocols, max 512 characters, download timeout 10s |
last_id | string | No | Reuse last task input | image_id from task return (not task_id), if provided, image input can be omitted |
sync | int | No | Synchronous/Asynchronous
Default: 0 Options: 0, 1 | 1=sync, 0=async |
ID Photo Specification Parameters | ||||
spec_id | int | No | Specification ID | Specification includes size, background color, face size, file size |
dpi | int | No | Resolution DPI
Default: 300 | Min 10, max 1000 |
px_width | int | No | Pixel width | Can pass (px_width, px_height) or (mm_width, mm_height), default (295, 413), <1800 pixels |
px_height | int | No | Pixel height | Used with px_width, <1800 pixels |
mm_width | int | No | Millimeter width | Used with mm_height, <180mm |
mm_height | int | No | Millimeter height | Used with mm_width, <180mm |
Background Color Parameters | ||||
change_bg | int | No | Whether to cutout and change background
Default: 1 Options: 0, 1 | 0 or 1 |
bg_color | string | No | Background color | Hex format, common colors: white FFFFFF, red FF0000, blue 438EDB, default white |
bg_color2 | string | No | Gradient background color | Hex format, background gradients from top bg_color to bottom bg_color2, default empty |
Face Size Constraint Parameters | ||||
face_width | int | No | Face width | Face width (pixels) |
min_face_width | int | No | Minimum face width | Minimum face width (pixels) |
max_face_width | int | No | Maximum face width | Maximum face width (pixels) |
face_height | int | No | Face height | Face height (pixels) |
min_face_height | int | No | Minimum face height | Minimum face height (pixels) |
max_face_height | int | No | Maximum face height | Maximum face height (pixels) |
head_top | int | No | Head top distance | Distance from head top to top edge (pixels) |
min_head_top | int | No | Minimum head top | Minimum distance from head top (pixels) |
max_head_top | int | No | Maximum head top | Maximum distance from head top (pixels) |
chin_top | int | No | Chin top distance | Distance from chin to top edge (pixels) |
min_chin_top | int | No | Minimum chin top | Minimum distance from chin (pixels) |
max_chin_top | int | No | Maximum chin top | Maximum distance from chin (pixels) |
eyes_top | int | No | Eyes top distance | Distance from eyes to top edge (pixels) |
min_eyes_top | int | No | Minimum eyes top | Minimum distance from eyes (pixels) |
max_eyes_top | int | No | Maximum eyes top | Maximum distance from eyes (pixels) |
Beauty Enhancement Parameters | ||||
auto_bright | int | No | Auto brighten
Default: 0 Options: 0, 1 | 0 or 1, whether to auto adjust brightness |
bright_factor | float | No | Brightness intensity
Default: 0.5 | [0, 1], brightness coefficient |
auto_smooth | int | No | Auto smooth skin
Default: 0 Options: 0, 1 | 0 or 1, whether to auto smooth skin |
smooth_factor | float | No | Smoothing intensity
Default: 0.5 | [0, 1], smoothing coefficient |
auto_thin_face | int | No | Auto slim face
Default: 0 Options: 0, 1 | 0 or 1, whether to auto slim face |
thin_face_factor | float | No | Face slimming intensity
Default: 0.5 | [0, 1], face slimming coefficient |
auto_sharp | int | No | Auto sharpen
Default: 0 Options: 0, 1 | 0 or 1, whether to auto sharpen |
sharp_factor | float | No | Sharpening intensity
Default: 0.5 | [0, 1], sharpening coefficient |
Outfit Change Parameters | ||||
clothes_id | string | No | man_1~man_20, woman_1~woman_20, child_1~child_10, default empty | |
Preview and Watermark Parameters | ||||
preview | int | No | Preview only
Default: 0 Options: 0, 1 | 0 or 1, preview has watermark and does not consume credits |
File Size Control Parameters | ||||
quality | int | No | Compression quality
Default: 92 | [1, 100], larger value means larger file size |
min_file_size | int | No | Target minimum size (Bytes) | [0, inf], e.g. 10240 means min file size 10KB, only takes effect when quality is empty, default empty |
max_file_size | int | No | Target maximum size (Bytes) | [0, inf], only takes effect when quality is empty, default empty |
Label Parameters | ||||
add_label | int | No | Add label
Default: 0 Options: 0, 1 | 0 or 1, whether to add label at bottom |
label_text | string | No | Label text | Label content at bottom, default empty |
label_height | int | No | Label height
Default: 30 | Label height at bottom (pixels) |
Layout Parameters | ||||
layout | int | No | Layout
Default: 0 Options: 0, 1 | 0 or 1, whether to return layout |
layout_vertical | int | No | Layout direction
Default: 0 Options: 0, 1 | 0 or 1, horizontal or vertical layout, default horizontal |
layout_size | string | No | Paper size
Default: 5inch Options: 5inch, 6inch | "5inch" or "6inch", 5-inch or 6-inch layout |
layout_bg_color | string | No | Canvas background color | Hex format, e.g. white FFFFFF, default gray |
layout_qr_code_data | string | No | QR code data | Layout additional QR code data, default empty |
layout_qr_code_size | int | No | QR code size
Default: 290 | Layout additional QR code size in pixels |
layout_label_text | string | No | Canvas label text | Layout additional text, use \n for line breaks, default empty |
Response Examples
1. Asynchronous Mode (sync=0)
Success Response Example
{
"status": 200,
"message": "ok",
"data": {
"task_id": "94806a3f-1173-4afb-9bcc-3ff19c0981f4"
}
}
Error Response Example
{
"status": 401,
"message": "Invalid API key"
}
Response Fields
Field | Type | Description |
---|---|---|
status | int | 200 for success, non-200 for failure. Please refer to HTTP response codes |
message | string | Response message description |
data | object | - |
├─ task_id | string | Task ID, used to query the ID photo result |
2. Polling for ID Photo Result
Note: Total polling time should not exceed 5 minutes. Recommended polling interval is 1 second. Exit polling when the result is obtained or an error occurs.
- Request URL:
https://techsz.aoscdn.com/api/tasks/visual/external/idphoto/{task_id}
- HTTP Method: GET
URL Parameters
a. Header Information
Parameter | Type | Description |
---|---|---|
X-API-KEY | string | Your exclusive API Key |
b. URL Path Parameters
Parameter | Type | Description |
---|---|---|
task_id | string | The task_id returned from the first ID photo request |
Success Response Examples
Processing
{
"status": 200,
"message": "success",
"data": {
"progress": 21,
"state": 4
}
}
Completed
{
"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"
}
}
Error Response Examples
Request Failed
{
"status": 401,
"message": "Invalid API key"
}
Processing Failed
{
"status": 200,
"message": "success",
"data": {
"created_at": 1634884056,
"processed_at": 1634884056,
"progress": 0,
"state": -1,
"task_id": "8576761c-fbe5-48a7-9620-18f9ebb132b3"
}
}
Response Fields
Field | Type | Description |
---|---|---|
status | int | 200 for success, non-200 for failure. Please refer to HTTP response codes |
message | string | Response message description. If the ID photo processing fails, refer to this parameter or contact customer service with this information. |
data | object | - |
├─ state | int | state < 0 (Processing Failed) • -8: Processing timeout, maximum processing time is 30 seconds • -7: Invalid image file (e.g., corrupted image, wrong format) • -5: URL image exceeds size limit (15MB) • -3: Failed to download image from URL (please check if the URL is accessible) • -2: ID photo completed, but failed to upload to OSS • -1: ID photo processing failed state = 0 (Queued) state = 1 (Completed) state = 2 (Preparing) state = 3 (Waiting) state = 4 (Processing) Queued means the task is in the queue waiting for processing; Processing means the ID photo is being generated. |
├─ progress | int | Task processing progress (percentage), range: 0~100. 100 means completed, < 100 means in progress |
├─ task_id | string | Task ID. If processing fails, please contact customer service with this parameter |
├─ image | string | Download URL or base64 data of the processed ID photo result |
├─ image_id | string | The image_id returned from the task, not the task_id. Used for image reuse in next request, corresponding to the last_id input parameter |
├─ created_at | int | Task creation timestamp |
├─ processed_at | int | Timestamp when task processing started |
├─ completed_at | int | Task completion timestamp |
├─ time_elapsed | string | Time elapsed |
ID Photo Specifications List
spec_id | Category | Title | Size(mm) | Size(px) | DPI | Color Requirement |
---|---|---|---|---|---|---|
1101 | Common | Small 1 Inch | 22x32 | 260x378 | 300 | No Requirement |
1102 | Common | 1 Inch | 25x35 | 295x413 | 300 | No Requirement |
1103 | Common | Large 1 Inch | 33x48 | 390x567 | 300 | No Requirement |
1104 | Common | Small 2 Inch | 35x45 | 413x531 | 300 | No Requirement |
1105 | Common | 2 Inch | 35x49 | 413x579 | 300 | No Requirement |
1106 | Common | Large 2 Inch | 35x53 | 413x626 | 300 | No Requirement |
1107 | Common | 3 Inch | 55x84 | 649x991 | 300 | No Requirement |
1108 | Common | 4 Inch | 76x102 | 898x1205 | 300 | No Requirement |
1109 | Common | 5 Inch | 89x127 | 1051x1500 | 300 | No Requirement |
2101 | Government | Social Security Card | 26x32 | 358x441 | 350 | White |
2102 | Government | ID Card | 26x32 | 358x441 | 350 | White |
2103 | Government | Residence Permit | 26x32 | 358x441 | 350 | White |
2201 | Government | Health Certificate (1 Inch) | 25x35 | 295x413 | 300 | Blue, White |
2202 | Government | Health Certificate (Small 2 Inch) | 35x45 | 413x531 | 300 | Blue, White |
2203 | Government | Medical Insurance Card | 26x32 | 358x441 | 300 | White |
2301 | Government | Driver's License (Small 1 Inch) | 22x32 | 260x378 | 300 | White |
2401 | Government | Veteran Preferential Treatment Card | 30x37 | 352x440 | 300 | White |
3101 | Visa | Brazil Visa | 40x50 | 472x590 | 300 | White |
3102 | Visa | Iceland Visa | 40x50 | 472x590 | 300 | White |
3103 | Visa | Argentina Visa | 40x40 | 472x472 | 300 | White |
3105 | Visa | South Korea Visa | 35x45 | 413x531 | 300 | White |
3106 | Visa | Kenya Visa | 50x50 | 590x590 | 300 | White |
3107 | Visa | Malaysia Visa | 35x45 | 413x531 | 300 | White |
3108 | Visa | USA Visa | 51x51 | 602x602 | 300 | White |
3109 | Visa | Japan Visa | 45x45 | 531x531 | 300 | White |
3110 | Visa | Universal Visa | 35x45 | 413x531 | 300 | White |
3111 | Visa | Thailand Visa | 35x45 | 413x531 | 300 | White |
3112 | Visa | New Zealand Visa | 35x45 | 413x531 | 300 | White |
3113 | Visa | Italy Visa | 35x45 | 413x531 | 300 | White |
3114 | Visa | Israel Visa | 51x51 | 602x602 | 300 | White |
3115 | Visa | India Visa | 51x51 | 602x602 | 300 | White |
3116 | Visa | Vietnam Visa | 35x45 | 413x531 | 300 | Blue, Red, White |
3117 | Visa | Laos Visa | 51x51 | 602x602 | 300 | White |
3118 | Visa | France Visa | 35x45 | 413x531 | 300 | White |
3119 | Visa | Myanmar Visa | 35x45 | 413x531 | 300 | White |
3120 | Visa | Canada Visa | 35x45 | 413x531 | 300 | White |
3121 | Visa | Philippines Visa | 51x51 | 602x602 | 300 | White |
3202 | Visa | Overseas Passport Application Photo | 33x48 | 389x566 | 300 | White |
3301 | Visa | Taiwan Entry Permit | 35x45 | 413x531 | 300 | White |
3302 | Visa | Hong Kong & Macau Permit | 33x48 | 389x566 | 300 | White |
4101 | Student | Enrollment Photo (2 Inch) | 35x49 | 413x578 | 300 | Blue, Red, White |
4102 | Student | Enrollment Photo (1 Inch) | 25x35 | 295x413 | 300 | Blue, Red, White |
4103 | Enrollment | Hong Kong Student Registration | 40x50 | 472x590 | 300 | White |
4201 | Student | National Student Registration Photo | 26x32 | 307x378 | 150 | White |
4301 | Student | University Student Image Collection | 41x54 | 480x640 | 300 | Blue |
4401 | Student | Graduation Photo | 41x54 | 480x640 | 300 | Blue, White |
5101 | Examination | National Civil Service Exam (1 Inch) | 25x35 | 295x413 | 300 | Blue, White |
5130 | Examination | National Civil Service Exam (Small 2 Inch) | 35x45 | 413x531 | 300 | Blue, White |
5131 | Examination | National Civil Service Exam (2 Inch) | 35x49 | 413x579 | 300 | Blue, White |
5102 | Examination | Anhui Civil Service Exam | 25x35 | 413x531 | 300 | Blue, White |
5103 | Examination | Beijing Civil Service Exam | 34x45 | 401x531 | 300 | Blue, White |
5104 | Examination | Chengdu Civil Service Exam | 9x11 | 102x126 | 300 | Blue, White, Red |
5132 | Examination | Chengdu Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White |
5105 | Examination | Gansu Civil Service Exam | 35x49 | 413x579 | 300 | Blue, White |
5106 | Examination | Guangxi Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White |
5107 | Examination | Guangzhou Civil Service Exam | 35x49 | 295x413 | 300 | Blue, White |
5108 | Examination | Guizhou Civil Service Exam | 18x25 | 215x300 | 300 | Blue, White, Red |
5109 | Examination | Hainan Civil Service Exam | 35x45 | 413x531 | 300 | Blue |
5110 | Examination | Hebei Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White, Red |
5111 | Examination | Henan Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White, Red |
5112 | Examination | Heilongjiang Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White, Red |
5113 | Examination | Hubei Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White |
5114 | Examination | Hunan Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White |
5115 | Examination | Jiangsu Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White |
5116 | Examination | Jiangxi Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White |
5117 | Examination | Ningxia Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White |
5118 | Examination | Qinghai Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White |
5119 | Examination | Shandong Civil Service Exam | 35x49 | 413x579 | 300 | Blue, White, Red |
5120 | Examination | Shanxi Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White, Red |
5121 | Examination | Shanghai Civil Service Exam | 13x17 | 150x200 | 300 | Blue, White |
5122 | Examination | Shaanxi Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White |
5123 | Examination | Shenzhen Civil Service Exam | 35x53 | 413x626 | 300 | Blue, White, Red |
5124 | Examination | Sichuan Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White |
5125 | Examination | Tibet Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White |
5126 | Examination | Xinjiang Civil Service Exam | 35x45 | 413x531 | 300 | Blue, White |
5127 | Examination | Yunnan Civil Service Exam | 35x49 | 413x579 | 300 | Blue, White, Red |
5128 | Examination | Shanxi Provincial Institution Exam | 25x35 | 295x413 | 300 | White |
5129 | Examination | Chongqing Civil Service Exam | 25x35 | 295x413 | 300 | Blue, White |
5201 | Examination | National Exam (2 Inch) | 35x45 | 413x531 | 300 | Blue, White |
5202 | Examination | National Exam (1 Inch) | 25x35 | 295x413 | 300 | Blue, White |
5203 | Examination | Gansu Province (National Exam) | 25x35 | 295x413 | 300 | Blue, White, Red |
5204 | Examination | Jiangxi Province (National Exam) | 35x53 | 413x626 | 300 | Blue, White |
5205 | Examination | Ningxia (National Exam) | 35x45 | 413x531 | 300 | Blue, White |
5206 | Examination | Qinghai Province (National Exam) | 35x45 | 413x531 | 300 | Blue, White |
5207 | Examination | Shanghai (National Exam) | 35x53 | 413x626 | 300 | Blue |
5301 | Examination | Adult College Entrance Exam | 40x54 | 480x640 | 300 | Blue |
5302 | Examination | Adult Self-study Exam | 40x54 | 480x640 | 300 | Blue, White |
5303 | Examination | Adult Self-study Exam | 25x34 | 300x400 | 300 | Blue, White |
5401 | Examination | College Entrance Exam (1 Inch) | 25x35 | 295x413 | 300 | Blue, White |
5402 | Examination | College Entrance Exam (Small 2 Inch) | 35x45 | 413x531 | 300 | Blue, White |
5403 | Examination | Shanghai High School Entrance Exam | 14x20 | 168x240 | 300 | Blue, White, Red |
5404 | Examination | Wuhan University Graduate Exam | 13x17 | 150x200 | 300 | Blue, White, Red |
5405 | Examination | Graduate Entrance Exam | 33x48 | 390x567 | 300 | Blue, White |
5406 | Examination | In-service Graduate Exam | 35x45 | 413x531 | 300 | Blue, White |
5501 | Examination | Mandarin Proficiency Test | 33x48 | 390x567 | 300 | Blue, White, Red |
5502 | Examination | Business English Exam | 35x49 | 413x579 | 300 | Blue, White |
5503 | Examination | Degree English | 33x48 | 390x567 | 300 | White |
5504 | Examination | English AB Level Exam (2 Inch) | 33x48 | 390x567 | 300 | Blue |
5505 | Examination | English AB Level Exam (144X192) | 12x16 | 144x192 | 300 | Blue, White |
5506 | Examination | English Level 3 Exam | 12x16 | 295x413 | 300 | Blue |
5507 | Examination | English CET-4 | 33x43 | 390x507 | 300 | Blue, White |
5508 | Examination | English CET-4 | 12x16 | 144x192 | 300 | Blue, White |
5509 | Examination | English CET-6 | 12x16 | 144x192 | 300 | Blue, White |
5510 | Examination | Self-study Degree Foreign Language Exam | 40x54 | 480x640 | 300 | Blue |
5601 | Examination | Securities Exam Registration | 18x25 | 215x300 | 300 | Blue, White, Red |
5602 | Examination | CPA Exam (1 Inch) | 25x35 | 295x413 | 300 | White |
5603 | Examination | CPA Exam (178x220) | 15x19 | 178x220 | 300 | White |
5701 | Examination | National Medical Exam | 25x35 | 295x413 | 300 | Blue, White |
5702 | Examination | Nurse Qualification Exam | 35x45 | 413x531 | 300 | White |
5703 | Examination | Pharmacist Qualification Exam (1 Inch) | 25x35 | 295x413 | 300 | White |
5801 | Examination | Computer Level Exam | 12x16 | 144x192 | 300 | White |
5802 | Examination | Youth Electronic Info Level Exam | 35x53 | 413x626 | 300 | Blue, Red |
5803 | Examination | Youth Robot Tech Level Exam | 35x53 | 413x626 | 300 | Blue, White |
5901 | Examination | BIM Skills Level Exam | 25x35 | 295x413 | 300 | White |
5902 | Examination | Health Professional Tech Qualification Exam (1 Inch) | 25x35 | 295x413 | 300 | White |
5903 | Examination | Level 1 Fire Engineer Exam | 25x35 | 295x413 | 300 | White |
5904 | Examination | Nursery Teacher Exam (1 Inch) | 25x35 | 295x413 | 300 | White |
5905 | Examination | National Judicial Exam | 35x53 | 413x626 | 300 | Blue, White, Red |
5906 | Examination | Referee Qualification Exam | 25x35 | 295x413 | 300 | Blue |
6101 | Qualification | Level 2 Constructor Certificate (1 Inch) | 25x35 | 295x413 | 300 | Blue, White |
6102 | Qualification | Level 2 Constructor Certificate (2 Inch) | 35x53 | 413x626 | 300 | Blue, White |
6103 | Qualification | Level 1 Constructor | 25x35 | 295x413 | 300 | White |
6201 | Qualification | Tour Guide License (1 Inch) | 25x35 | 295x413 | 300 | White |
6202 | Qualification | Tour Guide License (2 Inch) | 35x53 | 413x626 | 300 | White |
6302 | Qualification | Veterinary Qualification Certificate | 19x28 | 230x334 | 300 | Blue, White |
6303 | Qualification | Medical Practitioner Certificate (Small 2 Inch) | 35x45 | 413x531 | 300 | White |
6401 | Qualification | Teacher Qualification Certificate (300x400) | 25x34 | 300x400 | 300 | White |
6501 | Qualification | Insurance Professional Certificate (210x270) | 18x23 | 210x270 | 300 | White |
6502 | Qualification | Accounting Certificate (1 Inch) | 25x35 | 295x413 | 300 | White |
6601 | Qualification | Law Enforcement Certificate | 40x54 | 480x640 | 300 | White |