Dans ce tutoriel, nous allons couvrir comment implémenter l’approche asynchrone de Image Converter. Il vous suffit d’envoyer l’image source à SubmitWebPConversionTask ou à toute autre méthode d’API de soumission telle que SubmitBmpConversionTask, SubmitDicomConversionTask, etc. pour recevoir l’identificateur de tâche en réponse.

Après avoir reçu l’identificateur de tâche, vous devez vérifier l’état de la tâche en appelant la méthode GetConversionTaskStatus. Vous devez appeler la même méthode après quelques secondes de retard tant que l’état de la tâche est égal à « Waiting ». Une fois que vous avez reçu « Completed » de la méthode GetConversionTaskStatus, vous pouvez appeler la méthode DownloadResult pour télécharger l’image finale. Vous pouvez utiliser l’implémentation C# ci-dessous.

 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
async Task<string> SubmitWebPConversionTask(string filePathToConvert, string rapidApiKey)
{
    using (HttpClient httpClient = new HttpClient())
    {
        using (MultipartFormDataContent form = new MultipartFormDataContent())
        {
            form.Headers.Add("X-RapidAPI-Key", rapidApiKey);
            form.Add(new StringContent("true"), "lossy");
            var fileBytes = await File.ReadAllBytesAsync(filePathToConvert);
            var fileName = Path.GetFileName(filePathToConvert);
            form.Add(new ByteArrayContent(fileBytes, 0, fileBytes.Length), "file", fileName);

            using (var response = await httpClient.PostAsync("https://image-converter4.p.rapidapi.com/submitWebPConversionTask", form))
            {
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
        }
    }
}

async Task<string> GetConversionTaskStatus(string taskId, string rapidApiKey)
{
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey);

        using (var response = await httpClient.GetAsync($"https://image-converter4.p.rapidapi.com/getConversionTaskStatus?taskId={taskId}"))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }
    }
}

async Task<byte[]> DownloadResult(string taskId, string rapidApiKey)
{
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey);

        using (var response = await httpClient.GetAsync($"https://image-converter4.p.rapidapi.com/downloadResult?taskId={taskId}"))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsByteArrayAsync();
        }
    }
}

var rapidApiKey = "<YOUR RAPIDAPI KEY HERE>";
var filePathToConvert = "WebRenderer.png";
var taskId = await SubmitWebPConversionTask(filePathToConvert, rapidApiKey);
var retryCount = 0;
while (retryCount < 100)
{
    retryCount++;
    await Task.Delay(5000);
    var status = await GetConversionTaskStatus(taskId, rapidApiKey);
    if (status == "Completed")
    {
        var fileBytes = await DownloadResult(taskId, rapidApiKey);
        await File.WriteAllBytesAsync("image.webp", fileBytes);
        break;
    }
    else if (status == "Waiting")
    {
        continue;
    }
    else if (status == "Failed")
    {
        throw new Exception("Cannot convert image");
    }
    else
    {
        throw new Exception("Invalid status");
    }
}