SixLabors ImageSharp produces huge image files

4.2k views Asked by At

I use the below code to resize JPG files to 200x240 pixels. The attached example file has a size of 900x600 pixels and is only 84 kb. However when I save the resized file using ImageSharp, the produced image is 435 kb! Why is the smaller image has a bigger file size?

I noticed that the bit depth of the original image is 24 bits but ImageSharp stores it with 32 bits. How can I reduce this?

enter image description here

Resized image:

enter image description here

var thumbImage = image.Clone(x => x.GetCurrentSize());

                        if (thumbImage.Width > 200)
                        {
                            thumbImage.Mutate(m =>
                            {
                                m.Resize(new ResizeOptions
                                {
                                    Mode = ResizeMode.Min,
                                    Size = new Size(200, 0)
                                });
                            });
2

There are 2 answers

6
Usama Safi On

It took me some time to figure out how to do it for a bit-depth of 24, i wish they extended the Save method with more obvious parameters, anyway here is the code.

            image.Mutate(x => x
                 .Resize(new ResizeOptions
                 {
                     Mode = ResizeMode.Min,
                     Size = new Size(240,200)
                 }));
            Stream stream = new System.IO.FileStream("sample.png", FileMode.Create);
            var pngEncoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
            pngEncoder.ColorType = SixLabors.ImageSharp.Formats.Png.PngColorType.Rgb;

            image.SaveAsPng(stream, pngEncoder);
            stream.Dispose();

if you save as jpeg(like the original image you have here) you will get way smaller image size, and bit-depth will stay the same as the source.

    image.Save("sample.jpeg");
0
Deane On

I had the same problem -- when resizing PNG files, the resulting file size was twice as big as the original (even if the dimensions were smaller).

I fixed it by changing the color type of the encoder:

var encoder = new PngEncoder() { ColorType = PngColorType.Palette }

This made the file size smaller (seemingly in correct ratio with the reduction in dimensions). I have not noticed any perceptible change in image quality.