Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

C# Source Code


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

Join 244,261 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,237 people online right now. Registration is fast and FREE... Join Now!





Crop image with C#

This is a snippet for cropping an image. You could set this up with a draggable square so the user can chose where to crop. Values in here are hardcoded for my use

Submitted By: PsychoCoder
Actions:
Rating:
Views: 6,952

Language: C#

Last Modified: May 25, 2008
Instructions: Pass the name of the image, height & width and coordinates

Snippet


  1. //Namespace Reference
  2. using System.Drawing;
  3. using System.Drawing.Drawing2D;
  4. using System.Drawing.Imaging;
  5.  
  6. /// <summary>
  7. /// method for cropping an image.
  8. /// </summary>
  9. /// <param name="img">the image to crop</param>
  10. /// <param name="width">new height</param>
  11. /// <param name="height">new width</param>
  12. /// <param name="x"></param>
  13. /// <param name="y"></param>
  14. /// <returns></returns>
  15. public Image Crop(string img, int width, int height, int x, int y)
  16. {
  17.     try
  18.     {
  19.         Image image = Image.FromFile(img);
  20.         Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
  21.         bmp.SetResolution(80, 60);
  22.  
  23.         Graphics gfx = Graphics.FromImage(bmp);
  24.         gfx.SmoothingMode = SmoothingMode.AntiAlias;
  25.         gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
  26.         gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
  27.         gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
  28.         // Dispose to free up resources
  29.         image.Dispose();
  30.         bmp.Dispose();
  31.         gfx.Dispose();
  32.  
  33.         return bmp;
  34.     }
  35.     catch (Exception ex)
  36.     {
  37.         MessageBox.Show(ex.Message);
  38.         return null;
  39.     }           
  40. }

Copy & Paste


Comments


cipher_nemo 2008-07-17 13:22:03

Awesome, works like a charm! Thanks for the simple example to help me crop images in .NET and C#.

cipher_nemo 2008-07-17 13:22:59

Oh, one other thing I forgot to mention: don't dispose bmp before you return it. I had to remove that line in order to return the actual image.


Add comment


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





Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month