将一张图片处理成多张不用尺寸的图片 自动生成缩略图
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Drawing.Imaging; using System.Drawing; public partial class ImageHandler : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { foreach (string f in Request.Files.AllKeys) { CreateNewSizePic(sPath, sPath + fileName, fileName, ".jpg"); } } catch (Exception ex) { Response.Write("error"); } Response.End(); } /// <summary> /// 将一张图片处理成多张不用尺寸的图片 /// path 文件需要保存的路径(E:新建文件夹2) /// orifielpath 当前原图文件的路径(E:新建文件夹1.jpg) /// orifilename 原图文件名称(1.jpg) /// fileType 原图后缀名(.jpg) /// </summary> /// <param name="filename"></param> public static string CreateNewSizePic(string path, string orifielpath, string orifilename, string fileType) { Bitmap bm = new Bitmap(orifielpath); SaveThumbnail(bm, 310, 310, path, orifilename + "_310X310", fileType); SaveThumbnail(bm, 230, 230, path, orifilename + "_230X230", fileType); SaveThumbnail(bm, 160, 160, path, orifilename + "_160X160", fileType); SaveThumbnail(bm, 80, 80, path, orifilename + "_80X80", fileType); SaveThumbnail(bm, 60, 60, path, orifilename + "_60X60", fileType); return path; } private static void SaveThumbnail(Bitmap originBitmap, int width, int height, string directory, string filename, string extension) { var physicalPath = directory + filename + extension; using (var newImage = new Bitmap(width, height)) { using (var graphic = GetGraphic(originBitmap, newImage)) { graphic.DrawImage(originBitmap, 0, 0, width, height); using (var encoderParameters = new EncoderParameters(1)) { encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); newImage.Save(physicalPath, ImageCodecInfo.GetImageEncoders().Where(x => x.FilenameExtension.Contains(extension.ToUpperInvariant())).FirstOrDefault(), encoderParameters); } } } } private static Graphics GetGraphic(System.Drawing.Image originImage, Bitmap newImage) { newImage.SetResolution(originImage.HorizontalResolution, originImage.VerticalResolution); var graphic = Graphics.FromImage(newImage); graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; return graphic; } }