XUser
XUser

Reputation: 43

Reduce image size imagemagic

I have tried to compress image but has no success.

Look at my small experiment

            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

Could any one point me to right direction?

I have already read some details here ImageMagick: Lossless max compression for PNG?

Upvotes: 2

Views: 7797

Answers (1)

dlemstra
dlemstra

Reputation: 8163

It seems that you are using Magick.NET. That library has a class called ImageOptimizer that can be used to lossless compress the file. An example on how you could use that can be found here: 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);

It is still possible that your file cannot be reduced in size because it is already stored with the best compression.

Upvotes: 5

Related Questions