amin mohammadi
amin mohammadi

Reputation: 1053

Resize image to lowest size with minimum quality loss

I have this piece of code to resize picture:

public static void GetProductSmallThumbnail(string fileUrl, string fileName)
        {
            System.Drawing.Image.GetThumbnailImageAbort myCallback =
            new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            System.Drawing.Image img = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
                img = System.Drawing.Image.FromStream(fs);
                int orgwidth = img.Width;
                int orgheight = img.Height;

                int imgwidth = img.Width;
                int imgheight = img.Height;

                // if 240 is max width
                imgwidth = 240;
                imgheight = Convert.ToInt32((imgwidth * orgheight) / orgwidth);
                System.Drawing.Image myThumbnail = img.GetThumbnailImage(
                imgwidth, imgheight, myCallback, IntPtr.Zero);
                myThumbnail.Save(Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"));
            }
            finally
            {
                fs.Close();
            }

        }

Everything works correctly but the file size is much more than expected. For example I used this image for Input: enter image description here

The resulted image has correct width and height but the size is 89 KB, but I expect this image which is 7 KB

enter image description here

Upvotes: 1

Views: 59

Answers (1)

aliras
aliras

Reputation: 424

The Save function of System.Drawing.Image has an overload which accepts a format as its second parameter (see docs). To save your image in a format that is different from your original, pass the format to the save funtion:

myThumbnail.Save(
    Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"),
    ImageFormat.Jpeg);

Upvotes: 1

Related Questions