Crop image in ASP.Net (C#)
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. 🙂
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