/// <summary> /// 制作缩略图 /// </summary> /// <param name="fileName">原图路径</param> /// <param name="newFileName">新图路径</param> /// <param name="maxWidth">最大宽度</param> /// <param name="maxHeight">最大高度</param> public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight) { Image original = Image.FromFile(fileName); Size _newSize = ResizeImage(original.Width, original.Height, maxWidth, maxHeight); Image displayImage = new Bitmap(original, _newSize); try { displayImage.Save(newFileName, GetFormat(fileName)); } finally { original.Dispose(); } } /// <summary> /// 计算新尺寸 /// </summary> /// <param name="width">原始宽度</param> /// <param name="height">原始高度</param> /// <param name="maxWidth">最大新宽度</param> /// <param name="maxHeight">最大新高度</param> /// <returns></returns> private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight) { decimal MAX_WIDTH = (decimal)maxWidth; decimal MAX_HEIGHT = (decimal)maxHeight; decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT; int newWidth, newHeight; decimal originalWidth = (decimal)width; decimal originalHeight = (decimal)height; if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT) { decimal factor; // determine the largest factor if (originalWidth / originalHeight > ASPECT_RATIO) { factor = originalWidth / MAX_WIDTH; newWidth = Convert.ToInt32(originalWidth / factor); newHeight = Convert.ToInt32(originalHeight / factor); } else { factor = originalHeight / MAX_HEIGHT; newWidth = Convert.ToInt32(originalWidth / factor); newHeight = Convert.ToInt32(originalHeight / factor); } } else { newWidth = width; newHeight = height; } return new Size(newWidth, newHeight); }
来源:http://www.cnblogs.com/dongchunfeng/archive/2011/08/03/2125766.html