You specify resizing and cropping. If you want the height of the thumbnails to change with a fixed width, the answers provided will already work for you.
The mention of the crop makes me think that you may need a fixed sketch size, with a filled width, and any overflowed vertical part is cropped. If so, you will need to do some work. I recently needed something similar, and this is what I came up with.
This will create the original thumbnail, size and cropped so that the original image completely fills the target thumbnail, cropping any overflow. There will be no borders in the thumbnail, even if the aspect ratio of the original and the thumbnail is different.
public System.Drawing.Image CreateThumbnail(System.Drawing.Image image, Size thumbnailSize) { float scalingRatio = CalculateScalingRatio(image.Size, thumbnailSize); int scaledWidth = (int)Math.Round((float)image.Size.Width * scalingRatio); int scaledHeight = (int)Math.Round((float)image.Size.Height * scalingRatio); int scaledLeft = (thumbnailSize.Width - scaledWidth) / 2; int scaledTop = (thumbnailSize.Height - scaledHeight) / 2; // For portrait mode, adjust the vertical top of the crop area so that we get more of the top area if (scaledWidth < scaledHeight && scaledHeight > thumbnailSize.Height) { scaledTop = (thumbnailSize.Height - scaledHeight) / 4; } Rectangle cropArea = new Rectangle(scaledLeft, scaledTop, scaledWidth, scaledHeight); System.Drawing.Image thumbnail = new Bitmap(thumbnailSize.Width, thumbnailSize.Height); using (Graphics thumbnailGraphics = Graphics.FromImage(thumbnail)) { thumbnailGraphics.CompositingQuality = CompositingQuality.HighQuality; thumbnailGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; thumbnailGraphics.SmoothingMode = SmoothingMode.HighQuality; thumbnailGraphics.DrawImage(image, cropArea); } return thumbnail; } private float CalculateScalingRatio(Size originalSize, Size targetSize) { float originalAspectRatio = (float)originalSize.Width / (float)originalSize.Height; float targetAspectRatio = (float)targetSize.Width / (float)targetSize.Height; float scalingRatio = 0; if (targetAspectRatio >= originalAspectRatio) { scalingRatio = (float)targetSize.Width / (float)originalSize.Width; } else { scalingRatio = (float)targetSize.Height / (float)originalSize.Height; } return scalingRatio; }
To use your code, you can replace your call with OriginalImage.GetThumbnailImage as follows:
imThumbnailImage = CreateThumbnail(OriginalImage, new Size(width, height));
Please note that for portrait images, this code will actually shift the thumbnail view a little higher in the original image. This was done so that portrait photographs of people did not lead to headless torsos when miniatures were created. If you do not want this logic, simply delete the if block following the comment "portrait mode".