Exemplo n.º 1
0
 public static async void CompressImageAsync(string path, string FileName)
 {
     //create an instance of the TinyPngClient
     var png = new TinyPngClient("h81Ll9ZbzgR8YW9T3SkNBNpjVyHndl0n");
     //Putting it all together
     await png.Compress(path + "oldimage\\" + FileName).Download().SaveImageToDisk(path + "newimage\\" + FileName);
 }
Exemplo n.º 2
0
        public void ResizingCoverResizeOperationThrowsWithInvalidParams()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().Resize()));

            Assert.ThrowsAsync <ArgumentException>(async() => await pngx.Compress(Cat).Resize(new CoverResizeOperation(0, 150)));
            Assert.ThrowsAsync <ArgumentException>(async() => await pngx.Compress(Cat).Resize(new CoverResizeOperation(150, 0)));
        }
Exemplo n.º 3
0
        public async Task FunctionHandler(S3Event s3Event, ILambdaContext context)
        {
            foreach (var record in s3Event.Records)
            {
                if (!_supportedImageTypes.Contains(Path.GetExtension(record.S3.Object.Key).ToLower()))
                {
                    Console.WriteLine($"Object {record.S3.Bucket.Name}:{record.S3.Object.Key} is not a supported image type");
                    continue;
                }

                Console.WriteLine($"Determining whether image {record.S3.Bucket.Name}:{record.S3.Object.Key} has been compressed");

                // Get the existing tag set
                var taggingResponse = await _s3Client.GetObjectTaggingAsync(new GetObjectTaggingRequest
                {
                    BucketName = record.S3.Bucket.Name,
                    Key        = record.S3.Object.Key
                });

                if (taggingResponse.Tagging.Any(tag => tag.Key == "Compressed" && tag.Value == "true"))
                {
                    Console.WriteLine($"Image {record.S3.Bucket.Name}:{record.S3.Object.Key} has already been compressed");
                    continue;
                }

                // Get the existing image
                using (var objectResponse = await _s3Client.GetObjectAsync(record.S3.Bucket.Name, record.S3.Object.Key))
                    using (Stream responseStream = objectResponse.ResponseStream)
                    {
                        Console.WriteLine($"Compressing image {record.S3.Bucket.Name}:{record.S3.Object.Key}");

                        // Use TinyPNG to compress the image
                        TinyPngClient tinyPngClient    = new TinyPngClient(Environment.GetEnvironmentVariable("TinyPNG_API_Key"));
                        var           compressResponse = await tinyPngClient.Compress(responseStream);

                        var downloadResponse = await tinyPngClient.Download(compressResponse);

                        // Upload the compressed image back to S3
                        using (var compressedStream = await downloadResponse.GetImageStreamData())
                        {
                            Console.WriteLine($"Uploading compressed image {record.S3.Bucket.Name}:{record.S3.Object.Key}");

                            await _s3Client.PutObjectAsync(new PutObjectRequest
                            {
                                BucketName  = record.S3.Bucket.Name,
                                Key         = record.S3.Object.Key,
                                InputStream = compressedStream,
                                TagSet      = new List <Tag>
                                {
                                    new Tag
                                    {
                                        Key   = "Compressed",
                                        Value = "true"
                                    }
                                }
                            });
                        }
                    }
            }
        }
Exemplo n.º 4
0
        public async Task CompressionShouldThrowIfNoNonSuccessStatusCode()
        {
            var pngx = new TinyPngClient(apiKey);

            TinyPngClient.HttpClient = new HttpClient(new FakeResponseHandler().CompressAndFail());

            await Assert.ThrowsAsync <TinyPngApiException>(async() => await pngx.Compress(Cat));
        }
Exemplo n.º 5
0
        public async Task CompressionCount()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress()));

            var result = await pngx.Compress(Cat);

            Assert.Equal(99, result.CompressionCount);
        }
Exemplo n.º 6
0
        public async Task ResizingCoverResizeOperation()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().Resize()));

            var resizedImageByteData = await pngx.Compress(Cat).Resize(new CoverResizeOperation(150, 150)).GetImageByteData();

            Assert.Equal(5970, resizedImageByteData.Length);
        }
Exemplo n.º 7
0
        public async Task CompressionShouldThrowIfNoPathToFile()
        {
            var pngx = new TinyPngClient(apiKey);

            TinyPngClient.HttpClient = new HttpClient(new FakeResponseHandler().Compress());

            await Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.Compress(string.Empty));
        }
Exemplo n.º 8
0
        public async Task Compression()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress()));

            var result = await pngx.Compress(Cat);

            Assert.Equal("image/jpeg", result.Input.Type);
            Assert.Equal(400, result.Output.Width);
            Assert.Equal(400, result.Output.Height);
        }
Exemplo n.º 9
0
        public async Task CompressAndStoreToS3FooBar()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().S3AndFail()));

            var result = await pngx.Compress(Cat);

            await Assert.ThrowsAsync <TinyPngApiException>(async() =>
                                                           await pngx.SaveCompressedImageToAmazonS3(result,
                                                                                                    new AmazonS3Configuration(ApiKey, ApiAccessKey, "tinypng-test-bucket", "ap-southeast-2"), "path"));
        }
Exemplo n.º 10
0
        public void DownloadingOperationThrows()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().Download()));

            Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.Compress((string)null).Download());

            Task <Responses.TinyPngCompressResponse> nullCompressResponse = null;

            Assert.ThrowsAsync <ArgumentNullException>(async() => await nullCompressResponse.Download());
        }
Exemplo n.º 11
0
        public async Task DownloadingOperationThrowsOnNonSuccessStatusCode()
        {
            var pngx = new TinyPngClient(apiKey);

            TinyPngClient.HttpClient = new HttpClient(new FakeResponseHandler()
                                                      .Compress()
                                                      .DownloadAndFail());

            await Assert.ThrowsAsync <TinyPngApiException>(async() => await pngx.Compress(Cat).Download());
        }
Exemplo n.º 12
0
        public async Task CompressionAndDownloadAndGetUnderlyingStream()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().Download()));

            var downloadResult = await pngx.Compress(Cat)
                                 .Download()
                                 .GetImageStreamData();

            Assert.Equal(16646, downloadResult.Length);
        }
Exemplo n.º 13
0
        public async Task CompressAndStoreToS3Throws()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().S3()));

            var result = await pngx.Compress(Cat);

            await Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.SaveCompressedImageToAmazonS3(result, null, string.Empty));

            //S3 configuration has not been set
            await Assert.ThrowsAsync <InvalidOperationException>(async() => await pngx.SaveCompressedImageToAmazonS3(result, path: string.Empty));
        }
Exemplo n.º 14
0
        public async Task CompressionWithStreams()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress()));

            await using var fileStream = File.OpenRead(Cat);

            var result = await pngx.Compress(fileStream);

            Assert.Equal("image/jpeg", result.Input.Type);
            Assert.Equal(400, result.Output.Width);
            Assert.Equal(400, result.Output.Height);
        }
Exemplo n.º 15
0
        public async Task CompressAndStoreToS3WithOptionsPassedIntoConstructor()
        {
            var pngx = new TinyPngClient(apiKey,
                                         new AmazonS3Configuration(ApiKey, ApiAccessKey, "tinypng-test-bucket", "ap-southeast-2"),
                                         new HttpClient(new FakeResponseHandler().Compress().S3()));

            var result = await pngx.Compress(Cat);

            var sendToAmazon = (await pngx.SaveCompressedImageToAmazonS3(result, "path.jpg")).ToString();

            Assert.Equal("https://s3-ap-southeast-2.amazonaws.com/tinypng-test-bucket/path.jpg", sendToAmazon);
        }
Exemplo n.º 16
0
        public async Task CompressAndStoreToS3ShouldThrowIfS3HasNotBeenConfigured()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().S3()));

            var result = await pngx.Compress(Cat);

            await Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.SaveCompressedImageToAmazonS3(null, "bucket/path.jpg"));

            await Assert.ThrowsAsync <InvalidOperationException>(async() => await pngx.SaveCompressedImageToAmazonS3(result, string.Empty));

            await Assert.ThrowsAsync <InvalidOperationException>(async() => await pngx.SaveCompressedImageToAmazonS3(result, "bucket/path.jpg"));
        }
Exemplo n.º 17
0
        public async Task CompressionWithBytes()
        {
            var pngx = new TinyPngClient(apiKey);

            TinyPngClient.HttpClient = new HttpClient(new FakeResponseHandler().Compress());

            var bytes  = File.ReadAllBytes(Cat);
            var result = await pngx.Compress(bytes);

            Assert.Equal("image/jpeg", result.Input.Type);
            Assert.Equal(400, result.Output.Width);
            Assert.Equal(400, result.Output.Height);
        }
Exemplo n.º 18
0
        public async Task CompressionAndDownload()
        {
            var pngx = new TinyPngClient(apiKey);

            TinyPngClient.HttpClient = new HttpClient(new FakeResponseHandler()
                                                      .Compress()
                                                      .Download());

            var downloadResult = await pngx.Compress(Cat)
                                 .Download()
                                 .GetImageByteData();

            Assert.Equal(16646, downloadResult.Length);
        }
Exemplo n.º 19
0
        public void ResizingOperationThrows()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().Resize()));

            Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.Compress((string)null).Resize(150, 150));
            Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.Compress((string)null).Resize(null));
            Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.Compress(Cat).Resize(null));

            Task <Responses.TinyPngCompressResponse> nullCompressResponse = null;

            Assert.ThrowsAsync <ArgumentNullException>(async() => await nullCompressResponse.Resize(150, 150));

            Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() => await pngx.Compress(Cat).Resize(0, 150));
            Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() => await pngx.Compress(Cat).Resize(150, 0));
        }
Exemplo n.º 20
0
        public async Task CompressionAndDownloadAndWriteToDisk()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress().Download()));

            try
            {
                await pngx.Compress(Cat)
                .Download()
                .SaveImageToDisk(SavedCatPath);
            }
            finally
            {
                //try cleanup any saved file
                File.Delete(SavedCatPath);
            }
        }
Exemplo n.º 21
0
        async void CompressImages(List <string> filePathList, List <string> fileNameList)
        {
            LblToplam.Text  = filePathList.Count.ToString();
            PgBarDurum.Step = PgBarDurum.Maximum / filePathList.Count;
            for (int i = 0; i < filePathList.Count; i++)
            {
                using (var png = new TinyPngClient("Paste your TinyPng api Key"))
                {
                    await png.Compress(filePathList[i].ToString())
                    .Download()
                    .SaveImageToDisk("D:/test/" + fileNameList[i].ToString());

                    PgBarDurum.PerformStep();
                    lblCounter.Text = (i + 1).ToString();
                }
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// 利用TinyPNG接口压缩图片
 /// </summary>
 /// <param name="paths">图片路径</param>
 /// <returns>表示异步执行压缩图片的任务</returns>
 public async Task TinifyAsync(params string[] paths)
 {
     // 如果没有配置APIKEY
     if (string.IsNullOrEmpty(_apiKey))
     {
         await Task.CompletedTask;
     }
     using (var png = new TinyPngClient(_apiKey))
     {
         foreach (var path in paths)
         {
             await png.Compress(path)
             .Download()
             .SaveImageToDisk(path);
         }
     }
 }
Exemplo n.º 23
0
        public async Task CanBeCalledMultipleTimesWithoutExploding()
        {
            var pngx1 = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress()));

            var result1 = await pngx1.Compress(Cat);

            Assert.Equal("image/jpeg", result1.Input.Type);
            Assert.Equal(400, result1.Output.Width);
            Assert.Equal(400, result1.Output.Height);


            var pngx2 = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress()));

            var result2 = await pngx2.Compress(Cat);

            Assert.Equal("image/jpeg", result2.Input.Type);
            Assert.Equal(400, result2.Output.Width);
            Assert.Equal(400, result2.Output.Height);
        }
Exemplo n.º 24
0
        public async Task <string> Upload(MemoryStream file, string fileName)
        {
            using var client = new AmazonS3Client(EnvironmentVariables.AwsAccessKeyId,
                                                  EnvironmentVariables.AwsSecretAccessKey, RegionEndpoint.SAEast1);
            using var tinyClient = new TinyPngClient(EnvironmentVariables.TinyPngApiKey);

            var response = await tinyClient.Compress(file.ToArray()).Download().GetImageStreamData();

            var uploadRequest = new TransferUtilityUploadRequest
            {
                InputStream = response,
                Key         = $"uploads/{fileName}",
                BucketName  = EnvironmentVariables.AwsBucketName,
                CannedACL   = S3CannedACL.PublicRead
            };

            var fileTransferUtility = new TransferUtility(client);
            await fileTransferUtility.UploadAsync(uploadRequest);

            return("https://s3-sa-east-1.amazonaws.com/traba.io/uploads/" + fileName);
        }
Exemplo n.º 25
0
        public async Task CanBeCalledMultipleTimesWihtoutExploding()
        {
            using (var pngx = new TinyPngClient(apiKey))
            {
                TinyPngClient.HttpClient = new HttpClient(new FakeResponseHandler().Compress());

                var result = await pngx.Compress(Cat);

                Assert.Equal("image/jpeg", result.Input.Type);
                Assert.Equal(400, result.Output.Width);
                Assert.Equal(400, result.Output.Height);
            }

            using (var pngx = new TinyPngClient(apiKey))
            {
                TinyPngClient.HttpClient = new HttpClient(new FakeResponseHandler().Compress());

                var result = await pngx.Compress(Cat);

                Assert.Equal("image/jpeg", result.Input.Type);
                Assert.Equal(400, result.Output.Width);
                Assert.Equal(400, result.Output.Height);
            }
        }
Exemplo n.º 26
0
        public async Task CompressionAndDownload()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler()
                .Compress()
                .Download());

            var result = await pngx.Compress(Cat);

            var downloadResult = await pngx.Download(result);

            Assert.Equal(16646, (await downloadResult.GetImageByteData()).Length);
        }
Exemplo n.º 27
0
        public async Task ResizingOperationThrows()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler()
                .Compress()
                .Resize());

            var result = await pngx.Compress(Cat);

            await Assert.ThrowsAsync<ArgumentNullException>(async () => await pngx.Resize(null, 150, 150));
            await Assert.ThrowsAsync<ArgumentNullException>(async () => await pngx.Resize(null, null));
            await Assert.ThrowsAsync<ArgumentNullException>(async () => await pngx.Resize(result, null));
            await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () => await pngx.Resize(result, 0, 150));
            await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () => await pngx.Resize(result, 150, 0));

        }
Exemplo n.º 28
0
        public async Task ResizingCoverResizeOperation()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler()
                .Compress()
                .Resize());

            var result = await pngx.Compress(Cat);

            var resized = await pngx.Resize(result, new CoverResizeOperation(150, 150));

            var resizedImageByteData = await resized.GetImageByteData();

            Assert.Equal(5970, resizedImageByteData.Length);

        }
Exemplo n.º 29
0
        public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
        {
            context.Logger.Log("START");

            foreach (var record in dynamoEvent.Records)
            {
                context.Logger.Log($"Event ID: {record.EventID}");
                context.Logger.Log($"Event Name: {record.EventName}");
                string streamRecordJson = SerializeObject(record.Dynamodb);
                Console.WriteLine($"DynamoDB Record:");
                Console.WriteLine(streamRecordJson);

                if (!record.Dynamodb.NewImage.ContainsKey("image") || !record.Dynamodb.Keys.ContainsKey("id"))
                {
                    context.Logger.Log("Missing data.");
                    continue;
                }

                string id       = record.Dynamodb.Keys["id"].N;
                string filePath = record.Dynamodb.NewImage["image"].S;

                string fileName = Path.GetFileName(filePath);

                context.Logger.Log($"Record id: {id}");
                context.Logger.Log($"File name: {fileName}");

                if (_imageType != Path.GetExtension(fileName).ToLower())
                {
                    context.Logger.Log($"Not a supported image type");
                    continue;
                }

                try
                {
                    string bucketName = Environment.GetEnvironmentVariable("BucketName");
                    var    tinyPngKey = Environment.GetEnvironmentVariable("TinyPngKey");

                    using (var objectResponse = await _s3Client.GetObjectAsync(bucketName + "/original", fileName))
                        using (Stream responseStream = objectResponse.ResponseStream)
                        {
                            TinyPngClient tinyPngClient = new TinyPngClient(tinyPngKey);

                            using (var downloadResponse = await tinyPngClient.Compress(responseStream).Resize(150, 150).GetImageStreamData())
                            {
                                var putRequest = new PutObjectRequest
                                {
                                    BucketName  = bucketName + "/thumbnails",
                                    Key         = fileName,
                                    InputStream = downloadResponse,
                                    TagSet      = new List <Tag>
                                    {
                                        new Tag
                                        {
                                            Key = "Thumbnail", Value = "true"
                                        },
                                    },
                                };

                                putRequest.Metadata.Add(_metadataKey, id);

                                await _s3Client.PutObjectAsync(putRequest);
                            }
                        }
                }
                catch (Exception ex)
                {
                    context.Logger.Log($"Exception: {ex}");

                    // catch (AmazonS3Exception amazonS3Exception)
                    // {
                    //     if (amazonS3Exception.ErrorCode != null &&
                    //         (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    //         ||
                    //         amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                    //     {
                    //         Console.WriteLine("Check the provided AWS Credentials.");
                    //         Console.WriteLine(
                    //             "For service sign up go to http://aws.amazon.com/s3");
                    //     }
                    //     else
                    //     {
                    //         Console.WriteLine(
                    //             "Error occurred. Message:'{0}' when writing an object"
                    //             , amazonS3Exception.Message);
                    //     }
                    // }
                }
            }

            context.Logger.Log("END");
        }
Exemplo n.º 30
0
        public async Task CompressAndStoreToS3ShouldThrowIfS3HasNotBeenConfigured()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler()
                .Compress()
                .S3());

            var result = await pngx.Compress(Cat);

            await Assert.ThrowsAsync<ArgumentNullException>(async () => await pngx.SaveCompressedImageToAmazonS3(null, "bucket/path.jpg"));
            await Assert.ThrowsAsync<InvalidOperationException>(async () => await pngx.SaveCompressedImageToAmazonS3(result, string.Empty));
            await Assert.ThrowsAsync<InvalidOperationException>(async () => await pngx.SaveCompressedImageToAmazonS3(result, "bucket/path.jpg"));

        }
Exemplo n.º 31
0
        public async Task CompressAndStoreToS3Throws()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler()
                .Compress()
                .S3());

            var result = await pngx.Compress(Cat);

            await Assert.ThrowsAsync<InvalidOperationException>(async () => await pngx.SaveCompressedImageToAmazonS3(result, path: string.Empty));

        }
Exemplo n.º 32
0
        public async Task CompressAndStoreToS3WithOptionsPassedIntoConstructor()
        {
            var pngx = new TinyPngClient(apiKey, new AmazonS3Configuration(ApiKey, ApiAccessKey, "tinypng-test-bucket", "ap-southeast-2"));

            pngx.httpClient = new HttpClient(new FakeResponseHandler()
                .Compress()
                .S3());

            var result = await pngx.Compress(Cat);

            var sendToAmazon = (await pngx.SaveCompressedImageToAmazonS3(result, "path.jpg")).ToString();

            Assert.Equal("https://s3-ap-southeast-2.amazonaws.com/tinypng-test-bucket/path.jpg", sendToAmazon);

        }
Exemplo n.º 33
0
        public void CallingDisposeDoesNotBlowUpTheWorld()
        {
            var pngx = new TinyPngClient(apiKey);

            pngx.Dispose();
        }
Exemplo n.º 34
0
        public void CompressionShouldThrowIfNoUrlToFile()
        {
            var pngx = new TinyPngClient(apiKey, new HttpClient(new FakeResponseHandler().Compress()));

            Assert.ThrowsAsync <ArgumentNullException>(async() => await pngx.CompressFromUrl(string.Empty));
        }
Exemplo n.º 35
0
        public async Task CompressionShouldThrowIfNoPathToFile()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler().Compress());

            await Assert.ThrowsAsync<ArgumentNullException>(async () => await pngx.Compress(string.Empty));
        }
Exemplo n.º 36
0
        public async Task ResizingCoverResizeOperationThrowsWithInvalidParams()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler()
                .Compress()
                .Resize());

            var result = await pngx.Compress(Cat);

            await Assert.ThrowsAsync<ArgumentException>(async () => await pngx.Resize(result, new CoverResizeOperation(0, 150)));
            await Assert.ThrowsAsync<ArgumentException>(async () => await pngx.Resize(result, new CoverResizeOperation(150, 0)));

        }
Exemplo n.º 37
0
        public async Task CompressionWithStreams()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler().Compress());
            using (var fileStream = File.OpenRead(Cat))
            {
                var result = await pngx.Compress(fileStream);

                Assert.Equal("image/jpeg", result.Input.Type);
                Assert.Equal(400, result.Output.Width);
                Assert.Equal(400, result.Output.Height);
            }
        }
Exemplo n.º 38
0
        protected override async Task <int> ExecuteEngineAsync(CommandContext commandContext,
                                                               PngCompressSettings commandSettings,
                                                               IEngineManager engineManager)
        {
            var tinyPngKey = Environment.GetEnvironmentVariable("TinyPngKey") ??
                             throw new Exception(
                                       "TinyPng key not found. Expected value for environment variable \"TinyPngKey\"");

            var rootPath = engineManager.Engine.FileSystem.RootPath.FullPath;

            using var repo = new Repository(rootPath);
            var status = repo.RetrieveStatus();

            var modifiedPngs = status
                               .Where(_ => Path.HasExtension(".png"))
                               .Select(i => new NormalizedPath(Path.Combine(rootPath, i.FilePath)))
                               .ToImmutableList();

            var pngCompressor = new TinyPngClient(tinyPngKey);

            var pngs = engineManager.Engine.FileSystem
                       .GetInputFiles("**/*.png")
                       .Select(i => i.Path)
                       .Where(i => commandSettings.AllFiles || modifiedPngs.Contains(i))
                       .ToImmutableList();

            var totalPre  = 0L;
            var totalPost = 0L;

            var message = commandSettings.AllFiles ? "all files" : "checked out files";

            engineManager.Engine.Logger.Log(LogLevel.Information, "Beginning compression on {FileTypes}", message);

            foreach (var png in pngs)
            {
                var preSize = engineManager.Engine.FileSystem.GetFile(png.FullPath).Length;
                totalPre += preSize;

                await pngCompressor
                .Compress(png.FullPath)
                .Download()
                .SaveImageToDisk(png.FullPath);

                var postSize = engineManager.Engine.FileSystem.GetFile(png.FullPath).Length;
                totalPost += postSize;

                var percentCompressed = 1 - postSize / (decimal)preSize;
                engineManager.Engine.Logger.Log(LogLevel.Information,
                                                "Compressed {Path}. Reduced from {PreSize} to {PostSize} ({PercentCompressed:P})",
                                                png.Name,
                                                ByteSize.FromBytes(preSize).ToString(),
                                                ByteSize.FromBytes(postSize).ToString(),
                                                percentCompressed);
            }

            engineManager.Engine.Logger.Log(LogLevel.Information,
                                            "Compression complete. Reduced from {PreSize} to {PostSize}",
                                            ByteSize.FromBytes(totalPre).ToString(),
                                            ByteSize.FromBytes(totalPost).ToString());

            return(0);
        }
Exemplo n.º 39
0
        public async Task CompressionWithBytes()
        {
            var pngx = new TinyPngClient(apiKey);
            pngx.httpClient = new HttpClient(new FakeResponseHandler().Compress());

            var bytes = File.ReadAllBytes(Cat);
            var result = await pngx.Compress(bytes);

            Assert.Equal("image/jpeg", result.Input.Type);
            Assert.Equal(400, result.Output.Width);
            Assert.Equal(400, result.Output.Height);
        }