在网站开发过程中,有关图片展示的,几乎都存在一个缩略图的需求。 以下代码可以按“宽大等比例缩宽,高大等比例缩高”的原则,进行缩略图生成 static void Main(string[] args) { Console.WriteLine("请输入文件夹路径:"); string handleDirectory = Console.ReadLine(); if (Directory.Exists(handleDirectory)) { string[] files = Directory.GetFiles(handleDirectory); Image img = null; Image img150 = null; ImageFormat inFormat = null; foreach (string file in files) { if (file.IndexOf("_") < 0) { if (!File.Exists(file.Insert(file.IndexOf("."), "_150"))) { string extend = Path.GetExtension(file); switch (extend.ToLower()) { case ".jpg": inFormat = ImageFormat.Jpeg; break; case ".bmp": inFormat = ImageFormat.Bmp; break; case ".gif": inFormat = ImageFormat.Gif; break; case ".png": inFormat = ImageFormat.Png; break; case ".jpeg": inFormat = ImageFormat.Jpeg; break; default: break; } if (inFormat != null) { try { img = Image.FromFile(file); if (img != null) { int ox, oy, x, y; ox = img.Width; oy = img.Height; if (ox > oy) { x = 150; y = (oy * x) / ox; } else { y = 150; x = (ox * y) / oy; } Size newSize = new Size(x, y); using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) { using (Graphics canvas = Graphics.FromImage(newImage)) { canvas.SmoothingMode = SmoothingMode.AntiAlias; canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; canvas.DrawImage(img, new Rectangle(new Point(0, 0), newSize)); newImage.Save(file.Insert(file.IndexOf("."), "_150"), inFormat); } } } Console.WriteLine("已处理了图像:{0}", file); } catch { Console.WriteLine("处理图像:{0}时出错了", file); } finally { if (img != null) { img.Dispose(); } if (img150 != null) { img150.Dispose(); } } } } } } } else { Console.WriteLine("文件夹不存在"); } Console.WriteLine("处理完毕,请按任意建退出……"); Console.ReadKey(); } 上面代码是以150px去压缩的。