Вот решение, которое я использовал несколько раз.Это должно сначала изменить размер, а затем обрезать в зависимости от того, какой размер имеет избыток.Изображение не будет растягиваться.
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
protected Image imageCrop(Image image, int width, int height, AnchorPosition anchor)
{
int sourceWidth = image.Width;
int sourceHeight = image.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = (Convert.ToSingle(width) / Convert.ToSingle(sourceWidth));
nPercentH = (Convert.ToSingle(height) / Convert.ToSingle(sourceHeight));
if (nPercentH < nPercentW)
{
nPercent = nPercentW;
switch (anchor) {
case AnchorPosition.Top:
destY = 0;
break;
case AnchorPosition.Bottom:
destY = Convert.ToInt32(height - (sourceHeight * nPercent));
break;
default:
destY = Convert.ToInt32((height - (sourceHeight * nPercent)) / 2);
break;
}
}
else
{
nPercent = nPercentH;
switch (anchor) {
case AnchorPosition.Left:
destX = 0;
break;
case AnchorPosition.Right:
destX = Convert.ToInt32((width - (sourceWidth * nPercent)));
break;
default:
destX = Convert.ToInt32(((width - (sourceWidth * nPercent)) / 2));
break;
}
}
int destWidth = Convert.ToInt32((sourceWidth * nPercent));
int destHeight = Convert.ToInt32((sourceHeight * nPercent));
Bitmap bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(image, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
public enum Dimensions
{
Width,
Height
}
public enum AnchorPosition
{
Top,
Center,
Bottom,
Left,
Right
}
Вот пример вызова функции:
Image image = image.FromFile(imagePath);
Image thumb = imageCrop(image, 100, 100, AnchorPosition.Top);