using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Net; namespace YTSoft.Common { /// /// Thumbnail 的摘要说明。 /// public class Thumbnail { private Image srcImage; private string srcFileName; /// /// 创建 /// /// 原始图片路径 public bool SetImage(string FileName) { srcFileName = Utils.GetMapPath(FileName); try { srcImage = Image.FromFile(srcFileName); } catch { return false; } return true; } /// /// 回调 /// /// public bool ThumbnailCallback() { return false; } /// /// 生成缩略图,返回缩略图的Image对象 /// /// 缩略图宽度 /// 缩略图高度 /// 缩略图的Image对象 public Image GetImage(int Width,int Height) { Image img; Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback); img = srcImage.GetThumbnailImage(Width,Height,callb, IntPtr.Zero); return img; } /// /// 保存缩略图 /// /// /// public void SaveThumbnailImage(int Width,int Height) { switch(Path.GetExtension(srcFileName).ToLower()) { case ".png": SaveImage(Width, Height, ImageFormat.Png); break; case ".gif": SaveImage(Width, Height, ImageFormat.Gif); break; default: SaveImage(Width, Height, ImageFormat.Jpeg); break; } } /// /// 生成缩略图并保存 /// /// 缩略图的宽度 /// 缩略图的高度 /// 保存的图像格式 /// 缩略图的Image对象 public void SaveImage(int Width,int Height, ImageFormat imgformat) { if (imgformat != ImageFormat.Gif && (srcImage.Width > Width) || (srcImage.Height > Height)) { Image img; Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback); img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero); srcImage.Dispose(); img.Save(srcFileName, imgformat); img.Dispose(); } } #region Helper /// /// 保存图片 /// /// Image 对象 /// 保存路径 /// 指定格式的编解码参数 private static void SaveImage(Image image, string savePath, ImageCodecInfo ici) { //设置 原图片 对象的 EncoderParameters 对象 EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long) 100)); image.Save(savePath, ici, parameters); parameters.Dispose(); } /// /// 获取图像编码解码器的所有相关信息 /// /// 包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串 /// 返回图像编码解码器的所有相关信息 private static ImageCodecInfo GetCodecInfo(string mimeType) { ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders(); foreach(ImageCodecInfo ici in CodecInfo) { if(ici.MimeType == mimeType) return ici; } return null; } /// /// 计算新尺寸 /// /// 原始宽度 /// 原始高度 /// 最大新宽度 /// 最大新高度 /// private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight) { //此次2012-02-05修改过================= if (maxWidth <= 0) maxWidth = width; if (maxHeight <= 0) maxHeight = height; //以上2012-02-05修改过================= 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); } /// /// 得到图片格式 /// /// 文件名称 /// public static ImageFormat GetFormat(string name) { string ext = name.Substring(name.LastIndexOf(".") + 1); switch (ext.ToLower()) { case "jpg": case "jpeg": return ImageFormat.Jpeg; case "bmp": return ImageFormat.Bmp; case "png": return ImageFormat.Png; case "gif": return ImageFormat.Gif; default: return ImageFormat.Jpeg; } } #endregion /// /// 制作小正方形 /// /// 图片对象 /// 新地址 /// 长度或宽度 public static void MakeSquareImage(Image image, string newFileName, int newSize) { int i = 0; int width = image.Width; int height = image.Height; if (width > height) i = height; else i = width; Bitmap b = new Bitmap(newSize, newSize); try { Graphics g = Graphics.FromImage(b); //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.HighQuality; //清除整个绘图面并以透明背景色填充 g.Clear(Color.Transparent); if (width < height) g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle(0, (height-width)/2, width, width), GraphicsUnit.Pixel); else g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle((width-height)/2, 0, height, height), GraphicsUnit.Pixel); SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower())); } finally { image.Dispose(); b.Dispose(); } } /// /// 制作小正方形 /// /// 图片文件名 /// 新地址 /// 长度或宽度 public static void MakeSquareImage(string fileName, string newFileName, int newSize) { MakeSquareImage(Image.FromFile(fileName), newFileName, newSize); } /// /// 制作远程小正方形 /// /// 图片url /// 新地址 /// 长度或宽度 public static void MakeRemoteSquareImage(string url, string newFileName, int newSize) { Stream stream = GetRemoteImage(url); if (stream == null) return; Image original = Image.FromStream(stream); stream.Close(); MakeSquareImage(original, newFileName, newSize); } /// /// 制作缩略图 /// /// 图片对象 /// 新图路径 /// 最大宽度 /// 最大高度 public static void MakeThumbnailImage(Image original, string newFileName, int maxWidth, int maxHeight) { Size _newSize = ResizeImage(original.Width,original.Height,maxWidth, maxHeight); using (Image displayImage = new Bitmap(original, _newSize)) { try { displayImage.Save(newFileName, original.RawFormat); } finally { original.Dispose(); } } } /// /// 制作缩略图 /// /// 文件名 /// 新图路径 /// 最大宽度 /// 最大高度 public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight) { //2012-02-05修改过,支持替换 byte[] imageBytes = File.ReadAllBytes(fileName); Image img = Image.FromStream(new System.IO.MemoryStream(imageBytes)); MakeThumbnailImage(img, newFileName, maxWidth, maxHeight); //原文 //MakeThumbnailImage(Image.FromFile(fileName), newFileName, maxWidth, maxHeight); } #region 2012-2-19 新增生成图片缩略图方法 /// /// 生成缩略图 /// /// 源图路径(绝对路径) /// 缩略图路径(绝对路径) /// 缩略图宽度 /// 缩略图高度 /// 生成缩略图的方式 public static void MakeThumbnailImage(string fileName, string newFileName, int width, int height, string mode) { Image originalImage = Image.FromFile(fileName); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW"://指定高宽缩放(可能变形) break; case "W"://指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H"://指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut"://指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 Bitmap b = new Bitmap(towidth, toheight); try { //新建一个画板 Graphics g = Graphics.FromImage(b); //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower())); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); b.Dispose(); } } #endregion #region 2012-10-30 新增图片裁剪方法 /// /// 裁剪图片并保存 /// /// 源图路径(绝对路径) /// 缩略图路径(绝对路径) /// 缩略图宽度 /// 缩略图高度 /// 裁剪宽度 /// 裁剪高度 /// X轴 /// Y轴 public static bool MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y) { byte[] imageBytes = File.ReadAllBytes(fileName); Image originalImage = Image.FromStream(new System.IO.MemoryStream(imageBytes)); Bitmap b = new Bitmap(cropWidth, cropHeight); try { using (Graphics g = Graphics.FromImage(b)) { //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new Rectangle(0, 0, cropWidth, cropHeight), X, Y, cropWidth, cropHeight, GraphicsUnit.Pixel); Image displayImage = new Bitmap(b, maxWidth, maxHeight); SaveImage(displayImage, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower())); return true; } } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); b.Dispose(); } } #endregion /// /// 制作远程缩略图 /// /// 图片URL /// 新图路径 /// 最大宽度 /// 最大高度 public static void MakeRemoteThumbnailImage(string url, string newFileName, int maxWidth, int maxHeight) { Stream stream = GetRemoteImage(url); if(stream == null) return; Image original = Image.FromStream(stream); stream.Close(); MakeThumbnailImage(original, newFileName, maxWidth, maxHeight); } /// /// 获取图片流 /// /// 图片URL /// private static Stream GetRemoteImage(string url) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "GET"; request.ContentLength = 0; request.Timeout = 20000; HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); return response.GetResponseStream(); } catch { return null; } } } }