locked
Compress images RRS feed

  • Question

  • User-352524747 posted

    I'm looking for a simple function to reduce the image size before uploading to database. How to compress a big size image?

    Sunday, February 28, 2016 10:17 PM

Answers

  • User-804348187 posted

    private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath) //Based on scalefactor image size will vary, 0.5 default set for scalefactor.
    {
    using (var image = Image.FromStream(sourcePath))
    {
    var newWidth = (int)(image.Width * scaleFactor);
    var newHeight = (int)(image.Height * scaleFactor);
    var thumbnailImg = new Bitmap(newWidth, newHeight);
    var thumbGraph = Graphics.FromImage(thumbnailImg);
    thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
    thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
    var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
    thumbGraph.DrawImage(image, imageRectangle);
    thumbnailImg.Save(targetPath, image.RawFormat);
    }
    }

    Let me know if you have any query.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 29, 2016 5:49 AM

All replies

  • User-804348187 posted

    private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath) //Based on scalefactor image size will vary, 0.5 default set for scalefactor.
    {
    using (var image = Image.FromStream(sourcePath))
    {
    var newWidth = (int)(image.Width * scaleFactor);
    var newHeight = (int)(image.Height * scaleFactor);
    var thumbnailImg = new Bitmap(newWidth, newHeight);
    var thumbGraph = Graphics.FromImage(thumbnailImg);
    thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
    thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
    var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
    thumbGraph.DrawImage(image, imageRectangle);
    thumbnailImg.Save(targetPath, image.RawFormat);
    }
    }

    Let me know if you have any query.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 29, 2016 5:49 AM
  • User-352524747 posted

    Let me know if you have any query.

    Im using WebImages. Does your code reduce the size of an image? If yes, how to get bytes of the image after compression?

    Tuesday, March 1, 2016 11:27 PM