Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 137,225 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,088 people online right now. Registration is fast and FREE... Join Now!





Resize an image in C#

This is a snippet for resizing an image based on a percentage. If the user wants the image to be 75% of the original then pass the number 75

Submitted By: PsychoCoder
Actions:
Rating:
Views: 2,548

Language: C#

Last Modified: May 25, 2008
Instructions: Need references to System.Drawing, System.Drawing.Drawing2D, System.Drawing.Imaging Namespaces

Snippet


  1. //Namespace Reference
  2. using System.Drawing;
  3. using System.Drawing.Drawing2D;
  4. using System.Drawing.Imaging;
  5.  
  6. /// <summary>
  7. /// method for resizing an image
  8. /// </summary>
  9. /// <param name="img">the image to resize</param>
  10. /// <param name="percentage">Percentage of change (i.e for 105% of the original provide 105)</param>
  11. /// <returns></returns>
  12. public Image Resize(Image img, int percentage)
  13. {
  14.     //get the height and width of the image
  15.     int originalW = img.Width;
  16.     int originalH = img.Height;
  17.  
  18.     //get the new size based on the percentage change
  19.     int resizedW = (int)(originalW * percentage);
  20.     int resizedH = (int)(originalH * percentage);
  21.  
  22.     //create a new Bitmap the size of the new image
  23.     Bitmap bmp = new Bitmap(resizedW, resizedH);
  24.     //create a new graphic from the Bitmap
  25.     Graphics graphic = Graphics.FromImage((Image)bmp);
  26.     graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
  27.     //draw the newly resized image
  28.     graphic.DrawImage(img, 0, 0, resizedW, resizedH);
  29.     //dispose and free up the resources
  30.     graphic.Dispose();
  31.     //return the image
  32.     return (Image)bmp;
  33. }

Copy & Paste


Comments


thomerow 2008-11-18 03:45:12

If you only want to downscale images use InterpolationMode.HighQualityLinear. It is slightly faster than bicubic resizing and makes no visible difference.


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month