Image Compression in C#.

Sometime when we upload an Image to the server we need to compress it or we need another thumbnail image of it. In C# we can compress any image using few lines of code.

 protected void btnSave_Click(object o, EventArgs e)

        GenerateThumbnails(100,100, FileUpload1.PostedFile.InputStream, Server.MapPath(“~/Images/UserImage/t-” + fileName));



private void GenerateThumbnails(int width, int height, Stream sourcePath, string targetPath)
        using (var image = System.Drawing.Image.FromStream(sourcePath))
            var newWidth = width;
            var newHeight = height;
            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);


2 thoughts on “Image Compression in C#.

  1. 98354 448225Hey! I merely wish to give an enormous thumbs up for the great info youve got here on this post. I will likely be coming back to your blog for much more soon. 354256


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s