smart developer’s blog

This is a C# resource library! Free how to’s and best practices…

Crop image in ASP.Net (C#)

with one comment

You can use the custom method below:

public static void CropImageFile(string ImageFrom, string ImageTo, int targetW, int targetH)
Image imgPhoto = Image.FromFile(ImageFrom);
int targetX = (imgPhoto.Width – targetW) / 2;
int targetY = (imgPhoto.Height – targetH) / 2;

Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72, 72);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
new Rectangle(0, 0, targetW, targetH),
// Save out to memory and then to a file. We dispose of all objects to make sure the files don’t stay locked.
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)100);

ImageCodecInfo ici = GetEncoderInfo(“image/jpeg”);


bmPhoto.Save(ImageTo, ici, ep);

private static ImageCodecInfo GetEncoderInfo(String mimeType)
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j) { if(encoders[j].MimeType == mimeType) return encoders[j]; } return null; } [/sourcecode] If you combine this with the thumbnail auto-generation you can get a nice method that can generate a cropped thumbnail. 🙂


Written by smartdev

April 9, 2009 at 4:50 pm

Posted in .Net

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. Please note you can improve you image quality by changing line 10 from

    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;


    grPhoto.SmoothingMode = SmoothingMode.HighQuality;


    May 8, 2009 at 10:06 am

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: