0

Following this question Resize image proportionally with MaxHeight and MaxWidth constraints

I implemented the solution as follows:

public static class ImageResizer
{
    public static Image ResizeImage(String origFileLocation, int maxWidth, int maxHeight)
    {
        Image img = Image.FromFile(origFileLocation);

        if (img.Height < maxHeight && img.Width < maxWidth) return img;
        using (img)
        {
            Double xRatio = (double)maxWidth / img.Width;
            Double yRatio = (double)maxHeight / img.Height;
            Double ratio = Math.Max(xRatio, yRatio);

            int nnx = (int)Math.Floor(img.Width * ratio);
            int nny = (int)Math.Floor(img.Height * ratio);

            Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);
            using (Graphics gr = Graphics.FromImage(cpy))
            {
                gr.Clear(Color.Transparent);

                // This is said to give best quality when resizing images
                gr.SmoothingMode = SmoothingMode.HighQuality;
                gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;

                gr.DrawImage(img,
                    new Rectangle(0, 0, nnx, nny),
                    new Rectangle(0, 0, img.Width, img.Height),
                    GraphicsUnit.Pixel);
            }
            return cpy;
        }
    }

}

And then saving image this way:

                resized.Save(resizedFilePath, System.Drawing.Imaging.ImageFormat.Gif);

However, trying it, shrinking image, the result is very grained as you can see in this photo enter image description here

I would assume that shrinking image should result with no noticeable effects. Any ideas about it?

Community
  • 1
  • 1
dsb
  • 2,347
  • 5
  • 26
  • 43
  • try use only gr.InterpolationMode = InterpolationMode.HighQualityBicubic; some tutorial suggest this method and I used it in an old project but I don't remember the final result. – tezzo Sep 16 '15 at 13:20
  • have you tried to store it in a different format? just to make sure the problem is in the code above. – Ivan Stoev Sep 16 '15 at 13:32

2 Answers2

1

Yes. As @Ivan Stoev suggested. The problem is not with the resizing, rather in the saving method which appears to compress the image by default for some reason.

I used

resized.Save(resizedFilePath, System.Drawing.Imaging.ImageFormat.Png);

for saving and now everything seems fine. Thank you.

dsb
  • 2,347
  • 5
  • 26
  • 43
-2

resized.Save(resizedFilePath, System.Drawing.Imaging.ImageFormat.Png);

size large not optimation