locked
Shrunken Images Create Larger Files After Resizing RRS feed

  • Question

  • User-939035612 posted

    Hi,

    I successfully managed to shrink all uploaded images to widths of 700px. Good right? Wrong, because the new shrunken files are now much larger than the original files. My test case took 1600px wide image with a file size of 264KB and turned it into a 700 px wide image with a file size of 457KB.

    How is it possible to shrink the width of a file by 50% and have the end result be larger?

    The code I used is as follows:

    FileUpload FileUpload = (FileUpload)FormView1.FindControl("imageFileUpload");
            if (FileUpload.HasFile)
            {
                const string PictureDirectory = "~/uploads/images/";
                string Picture = PictureDirectory + FileUpload.FileName;
                string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(FileUpload.FileName);
                int iteration = 1;
                while (System.IO.File.Exists(Server.MapPath(Picture)))
                {
                    Picture = string.Concat(PictureDirectory, fileNameWithoutExtension, "-", iteration, System.IO.Path.GetExtension(FileUpload.FileName).ToLower());
                    iteration += 1;
                }
                Bitmap originalBMP = new Bitmap(FileUpload.FileContent);
                // Calculate the new image dimensions
                int origWidth = originalBMP.Width;
                int origHeight = originalBMP.Height;
                int sngRatio = origWidth / origHeight;
                int newWidth = 700;
                int newHeight = newWidth / sngRatio;
                // Create a new bitmap which will hold the previous resized bitmap
                Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
                // Create a graphic based on the new bitmap
                Graphics oGraphics = Graphics.FromImage(newBMP);
                // Set the properties for the new graphic file
                oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                // Draw the new graphic based on the resized bitmap
                oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                // Save the new graphic file to the server
                newBMP.Save(Server.MapPath(Picture));
                // Once finished with the bitmap objects, we deallocate them.
                originalBMP.Dispose();
                newBMP.Dispose();
                oGraphics.Dispose();
                e.Values["image"] = Picture;
            }

    Friday, May 8, 2020 3:23 AM

All replies