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;
grPhoto.DrawImage
(
imgPhoto,
new Rectangle(0, 0, targetW, targetH),
targetX,
targetY,
targetW,
targetH,
GraphicsUnit.Pixel
);
// 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”);

imgPhoto.Dispose();
grPhoto.Dispose();

bmPhoto.Save(ImageTo, ici, ep);
bmPhoto.Dispose();
}

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;

    to

    grPhoto.SmoothingMode = SmoothingMode.HighQuality;

    smartdev

    May 8, 2009 at 10:06 am


Leave a comment