我尝试压缩图像,但是没有成功。
看我的小实验
var results = new Dictionary<int, int>();
for (int i = 0; i <= 100; i++)
{
var stream = new MemoryStream();
image.Quality = i;
image.CompressionMethod = CompressionMethod.Zip;
image.Write(stream, MagickFormat.Png);
results[i] = stream.GetBuffer().Length;
stream.Flush();
}
var best = results.OrderBy(e => e.Value).First();
// the same length as for original image. quality doesn't work in this example - dictionary values are identical
有谁能给我指个方向吗?我已经在这里读了一些细节ImageMagick:无损最大压缩PNG?
看来你正在使用Magick.NET。该库有一个名为ImageOptimizer的类,可用于无损压缩文件。您可以在这里找到如何使用它的示例:https://github.com/dlemstra/Magick.NET/blob/main/samples/Magick.NET.Samples/LosslessCompression.cs
var snakewareLogo = new FileInfo(SampleFiles.OutputDirectory + "OptimizeTest.jpg");
File.Copy(SampleFiles.SnakewareJpg, snakewareLogo.FullName, true);
Console.WriteLine("Bytes before: " + snakewareLogo.Length);
var optimizer = new ImageOptimizer();
optimizer.LosslessCompress(snakewareLogo);
snakewareLogo.Refresh();
Console.WriteLine("Bytes after: " + snakewareLogo.Length);
仍然有可能您的文件无法缩小,因为它已经以最佳压缩方式存储。