简体   繁体   中英

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: 在此处输入图像描述

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

在此处输入图像描述

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM