Notice
-
The URL of the result image is valid for 1 hour. Please download the image file promptly.
-
You need to mark the area to be removed before starting the auto-removal. Mask Image and Rectangles are available for masking unwanted areas. For a Mask Image, the image size is the same as the source image. The removal area is white, and the rest of the area is black (as shown below). Please note that the removed area should not be larger than 50% of the source image. See the details in API Reference.
Source Image | Mask Image | Result Image |
---|---|---|
Supported Images
Format | Resolution | File size |
---|---|---|
jpg, jpeg, bmp, png, webp, tiff, tif, bitmap, raw, rgb, jfif, lzw | 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/watermark' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=0' \
-F 'image_url=YOU_IMG_URL'
-F 'mask_url=YOU_MASK_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/watermark/{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/watermark');
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", 'mask_url' => "YOU_MASK_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/watermark/".$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("rectangles", "[{\"x\":272,\"y\":1281,\"width\":543,\"height\":105}]")
.addFormDataPart("sync", "0")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/watermark")
.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/watermark/" + 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/inpaint",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
rectangles: '[{"x":0,"y":0,"width":20,"height":20}]',
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/inpaint/${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', 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]', 'image_url': IMAGE_NETWORK_URL, 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]'}
url = 'https://techsz.aoscdn.com/api/tasks/visual/inpaint'
# 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/inpaint/{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/watermark";
private static string API_KEY = "YOUR_API_KEY";
private static string imageUrl = "IMAGE_HTTP_URL";
private static string maskUrl = "MASK_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(maskUrl), "mask_url");
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)
{
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 Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/inpaint"
/// 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")
}
if let data = "0".data(using: .utf8) {
multipartFormData.append(data, withName: "sync")
}
if let rectangles = "[{\"x\":0,\"y\":0,\"width\":20,\"height\":20}]".data(using: .utf8) {
multipartFormData.append(rectangles, withName: "rectangles")
}
}, 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 imageUrlStr = data["image"] as? String {
completion(["image": imageUrlStr])
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/watermark"
)
// taskResponse
type taskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
type VisualWatermarkResponse struct {
Status uint `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
ReturnType uint `json:"return_type"`
Progress uint `json:"progress"`
State int `json:"state"`
TimeElapsed float64 `json:"time_elapsed"`
} `json:"data"`
}
func createTask() (string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
_ = writer.WriteField("mask_url", "YOU_MASK_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) (*VisualWatermarkResponse, 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 *VisualWatermarkResponse
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 < 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/watermark' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=1' \
-F 'image_url=YOU_IMG_URL'
-F 'mask_url=YOU_MASK_IMG_URL'
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/watermark');
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", 'mask_url' => "YOU_MASK_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"]);
} 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("rectangles", "[{\"x\":272,\"y\":1281,\"width\":543,\"height\":105}]")
.addFormDataPart("sync", "1")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/watermark")
.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/inpaint",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
sync: "1",
rectangles: '[{"x":0,"y":0,"width":20,"height":20}]',
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', 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]', 'image_url': IMAGE_NETWORK_URL, 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]'}
url = 'https://techsz.aoscdn.com/api/tasks/visual/inpaint'
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/watermark";
string imageUrl = "IMAGE_HTTP_URL";
string maskUrl = "MASK_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(maskUrl), "mask_url");
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 Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/inpaint"
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_SERVER_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "test.jpg", mimeType: "image/jpeg")
}
if let data = "1".data(using: .utf8) {
multipartFormData.append(data, withName: "sync")
}
if let rectangles = "[{\"x\":0,\"y\":0,\"width\":20,\"height\":20}]".data(using: .utf8) {
multipartFormData.append(rectangles, withName: "rectangles")
}
}, 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)
}
}
}
package api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"testing"
)
type VisualWatermarkResponse struct {
Status uint `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
ReturnType uint `json:"return_type"`
Progress uint `json:"progress"`
State int `json:"state"`
TimeElapsed float64 `json:"time_elapsed"`
} `json:"data"`
}
func TestwatermarkTechApi(t *testing.T) {
url := "https://techsz.aoscdn.com/api/tasks/visual/watermark"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
_ = writer.WriteField("sync", "1")
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
_ = writer.WriteField("mask_url", "YOU_MASK_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 *VisualWatermarkResponse
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/watermark' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=0' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'image_url=YOU_IMG_URL'
-F 'mask_url=YOU_MASK_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/watermark');
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", 'mask_url' => "YOU_MASK_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($data["data"]["image"]);
} 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("rectangles", "[{\"x\":272,\"y\":1281,\"width\":543,\"height\":105}]")
.addFormDataPart("callback_url", "YOUR_SERVER_URL")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/watermark")
.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/inpaint",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
rectangles: '[{"x":0,"y":0,"width":20,"height":20}]',
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, 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]', 'image_url': IMAGE_NETWORK_URL, 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]'}
url = 'https://techsz.aoscdn.com/api/tasks/visual/inpaint'
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/watermark";
string imageUrl = "IMAGE_HTTP_URL";
string maskUrl = "MASK_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(maskUrl), "mask_url");
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 Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/inpaint"
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_SERVER_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "test.jpg", mimeType: "image/jpeg")
}
if let data = "YOUR_SERVER_URL".data(using: .utf8) {
multipartFormData.append(data, withName: "callback_url")
}
if let rectangles = "[{\"x\":0,\"y\":0,\"width\":20,\"height\":20}]".data(using: .utf8) {
multipartFormData.append(rectangles, withName: "rectangles")
}
}, 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)
}
}
}
// 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 TestwatermarkTechApi(t *testing.T) {
url := "https://techsz.aoscdn.com/api/tasks/visual/watermark"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
_ = writer.WriteField("mask_url", "YOU_MASK_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 VisualWatermarkResponse struct {
Status uint `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
ReturnType uint `json:"return_type"`
Progress uint `json:"progress"`
State int `json:"state"`
TimeElapsed float64 `json:"time_elapsed"`
} `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",
"mask": "mask_data",
"mask_obj": "mask_obj_data",
"image_obj": "image_obj_data",
"return_type": 1,
"output_type": 1,
"type": "type_data",
"result_type": "result_type_data",
"time_elapsed": 2.5,
"progress": 100,
"state": 1,
"image_width": 800,
"image_height": 600
}
}`
// Parse JSON data into VisualWatermarkResponse struct
var response VisualWatermarkResponse
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.Image)
}
#Create a task
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/watermark' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=0' \
-F 'image_file=@/path/to/image.jpg'
-F 'mask_url=@/path/to/mask.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/watermark/{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/watermark');
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/watermark/".$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("rectangles", "[{\"x\":272,\"y\":1281,\"width\":543,\"height\":105}]")
.addFormDataPart("sync", "0")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/watermark")
.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/watermark/" + 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/inpaint",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
rectangles: '[{"x":0,"y":0,"width":20,"height":20}]',
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/inpaint/${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', 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]'}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/inpaint'
# 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/inpaint/{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/watermark";
private static string API_KEY = "YOUR_API_KEY";
private static string imagePath = "test.jpg";
private static string maskPath = "test_mask.jpg";
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();
var imageContent = new StreamContent(File.OpenRead(imagePath));
imageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
var maskImageContent = new StreamContent(File.OpenRead(maskPath));
maskImageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
multipartContent.Add(imageContent, "image_file", Path.GetFileName(imagePath));
multipartContent.Add(maskImageContent, "mask_file", Path.GetFileName(maskPath));
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)
{
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 Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/inpaint"
/// 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: "image_file", fileName: "test.jpg", mimeType: "image/jpeg")
if let data = "0".data(using: .utf8) {
multipartFormData.append(data, withName: "sync")
}
if let rectangles = "[{\"x\":0,\"y\":0,\"width\":20,\"height\":20}]".data(using: .utf8) {
multipartFormData.append(rectangles, withName: "rectangles")
}
}, 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 imageUrlStr = data["image"] as? String {
completion(["image": imageUrlStr])
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/watermark"
)
// taskResponse
type taskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
type VisualWatermarkResponse struct {
Status uint `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
ReturnType uint `json:"return_type"`
Progress uint `json:"progress"`
State int `json:"state"`
TimeElapsed float64 `json:"time_elapsed"`
} `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)
maskImagePath := "maskTest.jpg"
file, errMask := os.Open(maskImagePath)
if errMask != nil {
fmt.Println("Error: ", err)
return
}
maskPart, maskErr := writer.CreateFormFile("mask_file", filepath.Base(imagePath))
defer file.Close()
if maskErr != nil {
fmt.Println("Error: ", err)
return
}
io.Copy(maskPart, 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) (*VisualWatermarkResponse, 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 *VisualWatermarkResponse
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/watermark' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=1' \
-F 'image_file=@/path/to/image.jpg'
-F 'mask_file=@/path/to/mask.jpg'
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/watermark');
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"), 'mask_file' => new CURLFILE("/path/to/mask.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");
}
if ( $result["data"]["state"] == 1 ) {
// task success
var_dump($result["data"]["image"]);
} 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("rectangles", "[{\"x\":272,\"y\":1281,\"width\":543,\"height\":105}]")
.addFormDataPart("sync", "1")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/watermark")
.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/inpaint",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
sync: "1",
rectangles: '[{"x":0,"y":0,"width":20,"height":20}]',
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', 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]'}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/inpaint'
# 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/watermark";
string imagePath = "test.jpg";
string maskPath = "test_mask.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");
var maskImageContent = new StreamContent(File.OpenRead(maskPath));
maskImageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
content.Add(new StringContent(sync), "sync");
content.Add(imageContent, "image_file", Path.GetFileName(imagePath));
content.Add(maskImageContent, "mask_file", Path.GetFileName(maskPath));
//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 Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/inpaint"
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: "image_file", fileName: "test.jpg", mimeType: "image/jpeg")
if let data = "1".data(using: .utf8) {
multipartFormData.append(data, withName: "sync")
}
if let rectangles = "[{\"x\":0,\"y\":0,\"width\":20,\"height\":20}]".data(using: .utf8) {
multipartFormData.append(rectangles, withName: "rectangles")
}
}, 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)
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type VisualWatermarkResponse struct {
Status uint `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
ReturnType uint `json:"return_type"`
Progress uint `json:"progress"`
State int `json:"state"`
TimeElapsed float64 `json:"time_elapsed"`
} `json:"data"`
}
func main() {
apiKey := "YOUR_API_KEY"
url := "https://techsz.aoscdn.com/api/tasks/visual/watermark"
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
}
part, err := writer.CreateFormFile("image_file", filepath.Base(imagePath))
defer file.Close()
if err != nil {
fmt.Println("Error: ", err)
return
}
io.Copy(part, file)
maskImagePath := "maskTest.jpg"
file, errMask := os.Open(maskImagePath)
if errMask != nil {
fmt.Println("Error: ", err)
return
}
maskPart, maskErr := writer.CreateFormFile("mask_file", filepath.Base(imagePath))
defer file.Close()
if maskErr != nil {
fmt.Println("Error: ", err)
return
}
io.Copy(maskPart, 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 VisualWatermarkResponse
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/watermark' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'image_file=@/path/to/image.jpg'
-F 'mask_url=@/path/to/mask.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/watermark');
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);
// rectangles
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'sync' => 1,
'callback_url' => "YOUR_URL",
'image_file' => new CURLFILE("/path/to/image.jpg"), 'mask_file' => new CURLFILE("/path/to/mask.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($data["data"]["image"]);
} 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("rectangles", "[{\"x\":272,\"y\":1281,\"width\":543,\"height\":105}]")
.addFormDataPart("callback_url", "YOUR_SERVER_URL")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/watermark")
.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/inpaint",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
rectangles: '[{"x":0,"y":0,"width":20,"height":20}]',
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, 'rectangles': '[{"x":0,"y":0,"width":20,"height":20}]'}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/inpaint'
# 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/watermark";
string imagePath = "test.jpg";
string maskPath = "test_mask.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");
var maskImageContent = new StreamContent(File.OpenRead(maskPath));
maskImageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
content.Add(new StringContent(sync), "sync");
content.Add(imageContent, "image_file", Path.GetFileName(imagePath));
content.Add(maskImageContent, "mask_file", Path.GetFileName(maskPath));
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 Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/inpaint"
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: "image_file", fileName: "test.jpg", mimeType: "image/jpeg")
if let data = "YOUR_SERVER_URL".data(using: .utf8) {
multipartFormData.append(data, withName: "callback_url")
}
if let rectangles = "[{\"x\":0,\"y\":0,\"width\":20,\"height\":20}]".data(using: .utf8) {
multipartFormData.append(rectangles, withName: "rectangles")
}
}, 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)
}
}
}
// 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/watermark"
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)
maskImagePath := "maskTest.jpg"
file, errMask := os.Open(maskImagePath)
if errMask != nil {
fmt.Println("Error: ", err)
return
}
maskPart, maskErr := writer.CreateFormFile("mask_file", filepath.Base(imagePath))
defer file.Close()
if maskErr != nil {
fmt.Println("Error: ", err)
return
}
io.Copy(maskPart, 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 VisualWatermarkResponse struct {
Status uint `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
ReturnType uint `json:"return_type"`
Progress uint `json:"progress"`
State int `json:"state"`
TimeElapsed float64 `json:"time_elapsed"`
} `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 VisualWatermarkResponse struct
var response VisualWatermarkResponse
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.Image)
}