コード例 #1
0
        public async Task <byte[]> CompressAsync()
        {
            var  resImg             = SourceImageBytes;
            long lastCompressedSize = 0;

            //
            // Check if api keys have enough compress remain count
            while (ApiKeys.Any())
            {
                ApiKeys[0].CompressCount = await CompressRemainCountAsync(ApiKeys[0].Key);

                if (ApiKeys[0].CompressRemainCount <= 1)
                {
                    ApiKeys.RemoveAt(0);
                }
                else
                {
                    break;
                }
            }

            for (var repeatCount = 1; repeatCount <= RepeatCompressionNumber; repeatCount++)
            {
                using (var client = new WebClient())
                {
                    if (!ApiKeys.Any())
                    {
                        break;
                    }

                    var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"api:{ApiKeys[0].Key}"));
                    client.Headers.Add(HttpRequestHeader.Authorization, $"Basic {auth}");

                    do
                    {
                        await client.UploadDataTaskAsync(ApiUrl, resImg);

                        // Compression was successful, retrieve output from Location header.
                        resImg = await client.DownloadDataTaskAsync(client.ResponseHeaders["Location"]);

                        ApiKeys[0].CompressCount = int.Parse(client.ResponseHeaders["Compression-Count"]);

                        // call progress event to new compress level
                        OnProgressChanged(repeatCount, resImg, ApiKeys[0].CompressCount);
                        await ApiKeys[0].SaveCompressRemainCountAsync();

                        if (ApiKeys[0].CompressRemainCount <= 1)
                        {
                            ApiKeys.RemoveAt(0);
                        }

                        if (lastCompressedSize == resImg.LongLength)
                        {
                            goto EndOfCompress;
                        }

                        lastCompressedSize = resImg.LongLength;
                    } while (++repeatCount <= RepeatCompressionNumber && ApiKeys.Any());
                }
            }

EndOfCompress:
            return(resImg);
        }