在本教程中,我们将介绍如何实现图像转换器的异步方法。您只需将源图像发送到 SubmitWebPConversionTask 或任何其他提交 API 方法(如 SubmitBmpConversionTask、SubmitDicomConversionTask 等)即可接收任务标识符作为响应。

收到任务标识符后,您需要通过调用 GetConversionTaskStatus 方法检查任务状态。只要任务状态等于“Waiting”,您需要在几秒钟延迟后调用相同的方法。一旦您从GetConversionTaskStatus方法收到“Completed”,您就可以调用DownloadResult方法来下载最终图像。您可以使用下面的 Go Lang 实现。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main

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

func createReqBody(filePathToConvert string) (string, io.Reader, error) {
	var err error
	buf := new(bytes.Buffer)
	bw := multipart.NewWriter(buf)

	f, err := os.Open(filePathToConvert)
	if err != nil {
		return "", nil, err
	}
	defer f.Close()

	lossyField, _ := bw.CreateFormField("lossy")
	lossyField.Write([]byte("true"))

	_, fileName := filepath.Split(filePathToConvert)
	fw1, _ := bw.CreateFormFile("file", fileName)
	io.Copy(fw1, f)

	bw.Close()
	return bw.FormDataContentType(), buf, nil
}

func submitWebPConversionTask(filePath string, rapidApiKey string) (string, error) {
	contType, reader, err := createReqBody(filePath)
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", "https://image-converter4.p.rapidapi.com/submitWebPConversionTask", reader)
	req.Header.Add("Content-Type", contType)
	req.Header.Add("X-RapidAPI-Key", rapidApiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil || resp.StatusCode != 200 {
		fmt.Println("Cannot upload image to convert error:", err)
		return "", err
	}
	defer resp.Body.Close()
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

func getConversionTaskStatus(taskId string, rapidApiKey string) (string, error) {
	url := fmt.Sprintf("https://image-converter4.p.rapidapi.com/getConversionTaskStatus?taskId=%s", taskId)
	req, err := http.NewRequest("GET", url, nil)
	req.Header.Add("X-RapidAPI-Key", rapidApiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil || resp.StatusCode != 200 {
		fmt.Println("Cannot check conversion status of task with error:", err)
		return "", err
	}
	defer resp.Body.Close()
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

func downloadResult(taskId string, rapidApiKey string) ([]byte, error) {
	url := fmt.Sprintf("https://image-converter4.p.rapidapi.com/downloadResult?taskId=%s", taskId)
	req, err := http.NewRequest("GET", url, nil)
	req.Header.Add("X-RapidAPI-Key", rapidApiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil || resp.StatusCode != 200 {
		fmt.Println("Cannot download converted file with error:", err)
		return nil, err
	}
	defer resp.Body.Close()
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return b, nil
}

func main() {
	filePathToConvert := "<PATH OF SOURCE IMAGE TO CONVERT>"
	rapidApiKey := "<YOUR RAPIDAPI KEY HERE>"
	taskId, err := submitWebPConversionTask(filePathToConvert, rapidApiKey)
	if err != nil {
		panic(err)
	}
	retryCount := 0
	for retryCount < 100 {
		retryCount++
		time.Sleep(5 * time.Second)
		status, err := getConversionTaskStatus(taskId, rapidApiKey)
		if err != nil {
			panic(err)
		}
		if status == "Completed" {
			fileBytes, err := downloadResult(taskId, rapidApiKey)
			if err != nil {
				panic(err)
			}
			err = os.WriteFile("final_image.webp", fileBytes, 0644)
			if err != nil {
				panic(err)
			}
			break
		} else if status == "Waiting" {
			continue
		} else if status == "Failed" {
			panic(errors.New("Cannot convert image"))
		} else {
			panic(errors.New("Cannot convert image"))
		}
	}
}