И я разобрался с решением, необходимо использовать Graphics.DrawImage в качестве точки, в которой рассчитанные смещения могут быть предоставлены вместе с прямоугольником назначения, чтобы создать идеальный квадратный обрезанный квадрат.Ниже приведен улучшенный код:
//Obtain original image from input stream
using (var sourceImage = new Bitmap(Image.FromStream(inStream)))
{
//Obtain source dimensions and initialize scaled dimensions and crop offsets
int sourceWidth = sourceImage.Width;
int sourceHeight = sourceImage.Height;
int scaledSourceWidth = 0;
int scaledSourceHeight = 0;
int offsetWidth = 0;
int offsetHeight = 0;
//Calculate cropping offset
if (sourceWidth > sourceHeight)
{
offsetWidth = (sourceWidth - sourceHeight) / 2;
scaledSourceWidth = sourceWidth / (sourceHeight / thumbSize);
scaledSourceHeight = thumbSize;
}
else if (sourceHeight > sourceWidth)
{
offsetHeight = (sourceHeight - sourceWidth) / 2;
scaledSourceHeight = sourceHeight / (sourceWidth / thumbSize);
scaledSourceWidth = thumbSize;
}
//Create new thumbnail image of height and width defined in thumbSize
Bitmap thumbnail = new Bitmap(thumbSize, thumbSize, PixelFormat.Format24bppRgb);
thumbnail.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
using (var graphics = Graphics.FromImage(thumbnail))
{
//Draw source image scaled down with aspect ratio maintained onto the thumbnail with the offset
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.DrawImage(sourceImage, new Rectangle(0, 0, scaledSourceWidth, scaledSourceHeight), offsetWidth, offsetHeight, sourceWidth, sourceHeight, GraphicsUnit.Pixel);
//Push thumbnail onto stream for upload
using (MemoryStream stream = new MemoryStream())
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, Convert.ToInt64(Environment.GetEnvironmentVariable("ThumbnailQuality")));
var codecInfo = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
thumbnail.Save(stream, codecInfo, encoderParameters);
stream.Position = 0;
//Upload thumbnail
}
}
}
Любые улучшения или оптимизации приветствуются.