In ideal cases, creating image thumbnail would be just resizing the image into the correct size, preferably according to certain ratio. However, in my cases, I need to resize images into a specific size (100×100 pixels for instance).
I came across this post. The code actually does what I want, but not quite. First, it ‘draws’ the image in upper-left corner. Secondly, the background (of the resized image) is black. I did some changes to the code to draw the image in the center, and set the background to white.
double ratio;
Image originalImage = Image.FromFile("...");
if (originalImage.Width > originalImage.Height)
{
ratio = (double)100 / (double)originalImage.Width;
}
else
{
ratio = (double)100 / (double)originalImage.Height;
}
Bitmap thumbnail = new Bitmap(100, 100, originalImage.PixelFormat);
using (Graphics g = Graphics.FromImage(thumbnail))
{
g.Clear(Color.White);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
g.DrawImage(originalImage, (int)((100 - (originalImage.Width * ratio)) / 2), (int)((100 - (originalImage.Height * ratio)) / 2), (int)(originalImage.Width * ratio), (int)(originalImage.Height * ratio));
}
I only added one line of code, that is, Clear() to set the background color of the image, and modified the last line. Instead of drawing the image at (0,0), it draws in the center (That is, thumbnail_size - scaled_image_size divided by 2).
RSS feed for comments on this post · TrackBack URI
Leave a reply