private bool DoCompress(Stream stream, bool lossless) { ImageOptimizerHelper.CheckStream(stream); bool isCompressed = false; var startPosition = stream.Position; using (var images = new MagickImageCollection(stream, new MagickReadSettings() { Format = MagickFormat.Ico })) { foreach (var image in images) { if (image.Width > 255) { image.Format = MagickFormat.Png; var pngHelper = new PngHelper(this); var memoryStream = pngHelper.FindBestStreamQuality(image, out var bestQuality); image.Format = MagickFormat.Ico; if (memoryStream != null) { memoryStream.Dispose(); image.Quality = bestQuality; } } else { if (CanUseColormap(image, lossless)) { image.ClassType = ClassType.Pseudo; } } } using (var output = new MemoryStream()) { images.Write(output); if (output.Length < (stream.Length - startPosition)) { isCompressed = true; stream.Position = startPosition; output.Position = 0; StreamHelper.Copy(output, stream); stream.SetLength(startPosition + output.Length); } stream.Position = startPosition; } } return(isCompressed); }
private bool DoCompress(FileInfo file, bool lossless) { bool isCompressed = false; var settings = new MagickReadSettings() { Format = MagickFormat.Ico }; using (var images = new MagickImageCollection(file, settings)) { foreach (var image in images) { if (image.Width > 255) { image.Format = MagickFormat.Png; var pngHelper = new PngHelper(this); var memoryStream = pngHelper.FindBestStreamQuality(image, out var bestQuality); image.Format = MagickFormat.Ico; if (memoryStream != null) { memoryStream.Dispose(); image.Quality = bestQuality; } } else { if (CanUseColormap(image, lossless)) { image.ClassType = ClassType.Pseudo; } } } using (var tempFile = new TemporaryFile()) { images.Write(tempFile); if (tempFile.Length < file.Length) { isCompressed = true; tempFile.CopyTo(file); file.Refresh(); } } } return(isCompressed); }
private bool DoCompress(Stream stream, bool lossless) { ImageOptimizerHelper.CheckStream(stream); var isCompressed = false; var startPosition = stream.Position; using (var image = new MagickImage(stream)) { StartCompression(image, lossless); MemoryStream bestStream = null; try { var pngHelper = new PngHelper(this); bestStream = pngHelper.FindBestStreamQuality(image, out _); if (bestStream != null && bestStream.Length < (stream.Length - startPosition)) { isCompressed = true; stream.Position = startPosition; bestStream.Position = 0; bestStream.CopyTo(stream); stream.SetLength(startPosition + bestStream.Length); } stream.Position = startPosition; } finally { if (bestStream != null) { bestStream.Dispose(); } } } return(isCompressed); }