图片处理项目
图片处理也是一个大项目中的一小部分,别的不多说,直接上代码吧。
配置文件操作基类:

1 /// <summary> 2 /// 配置文件操作基类 3 /// </summary> 4 /// <typeparam name="T">配置信息实体类</typeparam> 5 public abstract class BaseConfig<T> where T : BaseConfig<T>, new() 6 { 7 private static string configFilePath = GetConfigPath(); 8 9 /// <summary> 10 /// 实例化对象 11 /// </summary> 12 /// <returns>配置信息实体</returns> 13 public static T Instance 14 { 15 get 16 { 17 T t = new T(); 18 return t.Get(); 19 } 20 } 21 22 private T Get() 23 { 24 Type configType = typeof(T); 25 26 if (!File.Exists(configFilePath)) 27 { 28 new T(); 29 } 30 31 using (var xmlTextReader = new XmlTextReader(configFilePath)) 32 { 33 var xmlSerializer = new XmlSerializer(configType); 34 return (T)xmlSerializer.Deserialize(xmlTextReader); 35 } 36 } 37 38 39 /// <summary> 40 /// 配置文件路径 41 /// </summary> 42 protected virtual string ConfigPath 43 { 44 get 45 { 46 return configFilePath; 47 } 48 49 set 50 { 51 configFilePath = value; 52 } 53 } 54 55 /// <summary> 56 /// 保存配置文件 57 /// </summary> 58 public void Save() 59 { 60 this.Save(this as T); 61 } 62 63 /// <summary> 64 /// 保存配置文件 65 /// </summary> 66 /// <param name="configInfo">配置信息临时变量</param> 67 protected void Save(T configInfo) 68 { 69 Type configType = typeof(T); 70 var xmlSerializer = new XmlSerializer(configType); 71 using (var xmlTextWriter = new XmlTextWriter(configFilePath, Encoding.UTF8)) 72 { 73 xmlTextWriter.Formatting = Formatting.Indented; 74 var xmlNamespace = new XmlSerializerNamespaces(); 75 xmlNamespace.Add(string.Empty, string.Empty); 76 xmlSerializer.Serialize(xmlTextWriter, configInfo, xmlNamespace); 77 } 78 } 79 80 /// <summary> 81 /// 获得配置文件名称 82 /// </summary> 83 /// <returns>配置文件所在路径</returns> 84 private static string GetConfigPath() 85 { 86 string configStr = typeof(T).Name; 87 if (configStr.ToLower().EndsWith("config")) 88 { 89 configStr = configStr.Substring(0, configStr.Length - 6); 90 } 91 string tmp = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; 92 tmp = System.Environment.CurrentDirectory; 93 94 return string.Concat(tmp, "\\", configStr, ".config"); 95 } 96 }
缩略图处理:
缩略模式:

1 /// <summary> 2 /// 缩略模式 3 /// HW:按照指定高宽进行设置缩略(可能变形) 4 /// H:指定高,宽按比例 5 /// W:指定宽,高按比例 6 /// CUTHW: 指定高宽裁减(不变形) 7 /// CUT:指定坐标和高宽进行裁剪某一区域 8 /// </summary> 9 public enum ThumbnailMode 10 { 11 HW = 1, 12 H = 2, 13 W = 3, 14 CUTHW = 4, 15 CUT = 5 16 }
缩略配置:

1 public class ThumbnailConfig : BaseConfig<ThumbnailConfig> 2 { 3 public ThumbnailConfig() 4 { 5 ThumMode = 1; 6 ThumbnailX = 0; 7 ThumbnailY = 0; 8 ThumbnailWidth = 100; 9 ThumbnailHeight = 200; 10 } 11 12 /// <summary> 13 /// 缩略图模式 14 /// </summary> 15 public int ThumMode { get; set; } 16 17 /// <summary> 18 /// 缩略图保存路径 19 /// </summary> 20 public string ThumbnailPath { get; set; } 21 22 /// <summary> 23 /// 缩略坐标X 24 /// </summary> 25 public int ThumbnailX { get; set; } 26 27 /// <summary> 28 /// 缩略坐标Y 29 /// </summary> 30 public int ThumbnailY { get; set; } 31 32 33 /// <summary> 34 /// 缩略宽度 35 /// </summary> 36 public int ThumbnailWidth { get; set; } 37 38 /// <summary> 39 /// 缩略高度 40 /// </summary> 41 public int ThumbnailHeight { get; set; } 42 }
缩略图处理类:

1 /// <summary> 2 /// 缩略图处理类 3 /// </summary> 4 public class Thumbnail 5 { 6 private ThumbnailConfig config = null; 7 private byte[] imgBuffer; 8 9 public ThumbnailConfig Config 10 { 11 get 12 { 13 return config; 14 } 15 set 16 { 17 config = value; 18 } 19 } 20 21 /// <summary> 22 /// 构造函数 23 /// </summary> 24 /// <param name="filePath">文件路径</param> 25 /// <param name="outputPath">输出文件路径</param> 26 /// <param name="x">x坐标</param> 27 /// <param name="y">y坐标</param> 28 /// <param name="width">缩略/裁剪宽度</param> 29 /// <param name="height">缩略/裁剪高度</param> 30 /// <param name="mode">缩略类型</param> 31 public Thumbnail(string filePath, string outputPath, int x, int y, int width, int height, ThumbnailMode mode) 32 { 33 this.Config = new ThumbnailConfig(); 34 this.FilePath = filePath; 35 Config.ThumbnailPath = outputPath; 36 Config.ThumbnailX = x; 37 Config.ThumbnailY = y; 38 Config.ThumbnailWidth = width; 39 Config.ThumbnailHeight = height; 40 Config.ThumMode = (int)mode; 41 } 42 43 /// <summary> 44 /// 构造函数 45 /// </summary> 46 /// <param name="filePath"></param> 47 /// <param name="outputPath"></param> 48 /// <param name="config"></param> 49 public Thumbnail(string filePath, ThumbnailConfig config) 50 { 51 this.Config = config; 52 this.FilePath = filePath; 53 } 54 55 /// <summary> 56 /// 构造函数 57 /// </summary> 58 /// <param name="buffer"></param> 59 /// <param name="config"></param> 60 public Thumbnail(byte[] buffer, ThumbnailConfig config) 61 { 62 this.imgBuffer = buffer; 63 this.Config = config; 64 } 65 66 /// <summary> 67 /// 文件路径 68 /// </summary> 69 public string FilePath { get; set; } 70 71 #region 保存缩略图 72 /// <summary> 73 /// 保存缩略图 74 /// </summary> 75 public void MakeThumbnailImage() 76 { 77 this.MakeThumbnailImage(false); 78 } 79 #endregion 80 81 #region 预览缩略图 82 /// <summary> 83 /// 获得缩略图后的图片流 84 /// </summary> 85 /// <returns></returns> 86 public byte[] GetThumbnailStream() 87 { 88 if (!string.IsNullOrEmpty(this.FilePath) && this.imgBuffer == null) 89 { 90 if (this.FilePath.Contains("http://")) 91 { 92 MakeRemoteThumbnailImage(null, (ThumbnailMode)Config.ThumMode, true); 93 } 94 } 95 MakeThumbnailImage(true); 96 if (imgBuffer != null) 97 { 98 return imgBuffer; 99 } 100 return null; 101 } 102 #endregion 103 104 #region 远程图片 105 /// <summary> 106 /// 根据URL获取图片流 107 /// </summary> 108 /// <param name="url">图片地址</param> 109 /// <returns></returns> 110 private Stream GetRemoteImage(string url) 111 { 112 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 113 request.ContentLength = 0; 114 request.Timeout = 2000; 115 HttpWebResponse response = null; 116 117 try 118 { 119 response = (HttpWebResponse)request.GetResponse(); 120 return response.GetResponseStream(); 121 } 122 catch 123 { 124 return null; 125 } 126 } 127 128 /// <summary> 129 /// 制作远程图片缩略图 130 /// </summary> 131 /// <param name="outputPath"></param> 132 /// <param name="width"></param> 133 /// <param name="height"></param> 134 /// <param name="mode"></param> 135 private void MakeRemoteThumbnailImage(string outputPath, ThumbnailMode mode, bool isPreview) 136 { 137 if (string.IsNullOrEmpty(this.FilePath)) 138 { 139 return; 140 } 141 Stream stream = GetRemoteImage(this.FilePath); 142 if (stream == null) 143 { 144 return; 145 } 146 Image img = Image.FromStream(stream); 147 MakeThumbnailImage(isPreview); 148 } 149 #endregion 150 151 #region 制作缩略图 152 /// <summary> 153 /// 制作缩略图 154 /// </summary> 155 /// <param name="img"></param> 156 /// <param name="mode"></param> 157 /// <returns></returns> 158 private void MakeThumbnailImage(bool isPreview) 159 { 160 Image sourceImg = null; 161 if (string.IsNullOrWhiteSpace(this.FilePath) || !File.Exists(this.FilePath)) 162 { 163 if (this.imgBuffer != null) 164 { 165 sourceImg = ImageDealHelper.StreamToImage(imgBuffer); 166 } 167 } 168 else 169 { 170 sourceImg = Image.FromFile(this.FilePath); 171 } 172 173 if (isPreview == false && string.IsNullOrEmpty(this.Config.ThumbnailPath)) 174 { 175 Config.ThumbnailPath = GetThumbnailFilePath(this.FilePath); 176 } 177 178 //如果传值超过原文件的高宽,将原文件的高宽设置为缩略高宽 179 int thumbWidth = Config.ThumbnailWidth; 180 int thumbHeight = Config.ThumbnailHeight; 181 thumbWidth = thumbWidth > sourceImg.Width ? sourceImg.Width : thumbWidth; 182 thumbHeight = thumbHeight > sourceImg.Height ? sourceImg.Height : thumbHeight; 183 184 if (sourceImg.RawFormat.Guid == ImageFormat.Gif.Guid) 185 { 186 int sourceImgSize = sourceImg.Width > sourceImg.Height ? sourceImg.Width : sourceImg.Height; 187 int customSize = thumbWidth > thumbHeight ? thumbWidth : thumbHeight; 188 double rate = (double)customSize / (double)sourceImgSize; 189 //Rectangle rec = GetRectangle(mode); 190 sourceImg.Dispose(); 191 if (imgBuffer != null) 192 { 193 imgBuffer = GifHelper.GetThumbnail(imgBuffer, rate, this.Config.ThumbnailPath, isPreview); 194 } 195 else 196 { 197 imgBuffer = GifHelper.GetThumbnail(this.FilePath, rate, Config.ThumbnailPath, isPreview); 198 } 199 //imgBuffer = GifHelper.GetThumbnail(this.FilePath, this.Width, this.Height, rec, this.ThumbnailPath, isPreview); //动态图片会变形 200 return; 201 } 202 203 Graphics g = Graphics.FromImage(sourceImg); 204 Rectangle rec = GetRectangle(sourceImg, (ThumbnailMode)Config.ThumMode); 205 206 Bitmap bitmap = new Bitmap(thumbWidth, thumbHeight); 207 Graphics graphics = Graphics.FromImage(bitmap); 208 graphics.Clear(Color.Transparent); 209 graphics.InterpolationMode = InterpolationMode.High; 210 graphics.SmoothingMode = SmoothingMode.HighQuality; 211 graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height); 212 graphics.DrawImage(sourceImg, new Rectangle(0, 0, thumbWidth, thumbHeight), rec, GraphicsUnit.Pixel); 213 214 try 215 { 216 if (isPreview) 217 { 218 MemoryStream ms = new MemoryStream(); 219 bitmap.Save(ms, sourceImg.RawFormat); 220 imgBuffer = ms.GetBuffer(); 221 } 222 else 223 { 224 bitmap.Save(Config.ThumbnailPath, sourceImg.RawFormat); 225 } 226 } 227 catch (Exception e) 228 { 229 throw e; 230 } 231 finally 232 { 233 sourceImg.Dispose(); 234 bitmap.Dispose(); 235 graphics.Dispose(); 236 } 237 } 238 #endregion 239 240 #region 获得缩略图的位置和大小 241 /// <summary> 242 /// 获取缩略图的位置和大小 243 /// </summary> 244 /// <param name="sourceImg"></param> 245 /// <param name="mode"></param> 246 /// <returns></returns> 247 private Rectangle GetRectangle(Image sourceImg, ThumbnailMode mode) 248 { 249 int x = 0; 250 int y = 0; 251 int sh = sourceImg.Height; 252 int sw = sourceImg.Width; 253 int thumbWidth = Config.ThumbnailWidth; 254 int thumbHeight = Config.ThumbnailHeight; 255 switch (mode) 256 { 257 case ThumbnailMode.HW: 258 break; 259 case ThumbnailMode.H: 260 thumbWidth = sourceImg.Height * thumbWidth / sourceImg.Width; 261 break; 262 case ThumbnailMode.W: 263 thumbHeight = sourceImg.Width * thumbHeight / sourceImg.Height; 264 break; 265 case ThumbnailMode.CUTHW: 266 if ((double)sourceImg.Width / (double)sourceImg.Height > (double)thumbWidth / (double)thumbHeight) 267 { 268 sh = sourceImg.Height; 269 sw = sourceImg.Height * thumbWidth / thumbHeight; 270 y = 0; 271 x = (sourceImg.Width - sw) / 2; 272 } 273 else 274 { 275 sw = sourceImg.Width; 276 sh = sourceImg.Width * thumbHeight / thumbWidth; 277 x = 0; 278 y = (sourceImg.Height - sh) / 2; 279 } 280 break; 281 case ThumbnailMode.CUT: 282 x = Config.ThumbnailX; 283 y = Config.ThumbnailY; 284 sw = Config.ThumbnailWidth; 285 sh = Config.ThumbnailHeight; 286 break; 287 default: break; 288 } 289 return new Rectangle(x, y, sw, sh); 290 } 291 #endregion 292 293 #region 获得缩略图文件保存名称 294 /// <summary> 295 /// 获得缩略图文件保存名称 296 /// </summary> 297 /// <param name="filePath"></param> 298 /// <returns></returns> 299 public string GetThumbnailFilePath(string filePath) 300 { 301 string extention = Path.GetExtension(this.FilePath); 302 string fileName = Path.GetFileNameWithoutExtension(this.FilePath); 303 string fullPath = Path.GetFullPath(this.FilePath); 304 return string.Concat(fullPath, fileName, "_", Config.ThumbnailWidth, "_", Config.ThumbnailHeight, extention); 305 } 306 #endregion 307 }
水印使用助手类:
水印类型
1 /// <summary> 2 /// 水印图片类型 3 /// TEXT:文本类型 4 /// Image:图片类型 5 /// </summary> 6 public enum WatermarkType 7 { 8 Text = 1, 9 Image = 2 10 }
水印位置:

/// <summary> /// 水印模式 /// Center:中间; /// CenterUp:中上; /// CenterDown:中下; /// LeftUp:左上; /// LeftDown:左下; /// RightUp:右上; /// RightDown:右下; /// Random:随机; /// Manual:手动设置 /// </summary> public enum WatermarkPosition { Center = 1, CenterUp = 2, CenterDown = 3, LeftUp = 4, LeftDown = 5, RightUp = 6, RightDown = 7, Random = 8, Manual = 9 }
水印配置信息类:

1 [Serializable] 2 public class WaterMarkConfig : BaseConfig<WaterMarkConfig> 3 { 4 /// <summary> 5 /// 构造函数 6 /// </summary> 7 public WaterMarkConfig() 8 { 9 IsEnableWatermark = false; 10 Type = (int)WatermarkType.Image; 11 WatermarkImagePath = "~/Content/"; 12 Opacity = 100; 13 Position = (int)WatermarkPosition.LeftDown; 14 Quality = 100; 15 Text = "动易网络"; 16 FontSize = 24; 17 FontColor = ColorTranslator.ToHtml(Color.Black); 18 FontStyle = 1; 19 FontBroderColor = ColorTranslator.ToHtml(Color.Black); 20 FontBroderSize = 0; 21 // WaterMarkSavePath = PathHelper.GetFilePath("~/Content/"); 22 } 23 24 /// <summary> 25 /// 是否开启水印处理功能 26 /// </summary> 27 [CategoryAttribute("常用"), Description("是否开启水印处理功能")] 28 public bool IsEnableWatermark { get; set; } 29 30 /// <summary> 31 /// 水印类型 32 /// </summary> 33 [CategoryAttribute("常用"), Description("{1:'文本类型',2:'图片类型'}")] 34 public int Type { get; set; } 35 36 #region 文字水印 37 /// <summary> 38 /// 水印文字内容 39 /// </summary> 40 [CategoryAttribute("文字水印"), Description("水印文字内容")] 41 public string Text { get; set; } 42 43 /// <summary> 44 /// 文字大小 45 /// </summary> 46 [CategoryAttribute("文字水印"), Description("文字大小")] 47 public int FontSize { get; set; } 48 49 /// <summary> 50 /// 字体名称 51 /// </summary> 52 [CategoryAttribute("文字水印"), Description("字体名称")] 53 public string FontFamily { get; set; } 54 55 /// <summary> 56 /// 字体颜色 57 /// </summary> 58 [CategoryAttribute("文字水印"), Description("字体颜色")] 59 public string FontColor { get; set; } 60 61 /// <summary> 62 /// 字体样式 63 /// </summary> 64 [CategoryAttribute("文字水印"), Description("字体样式")] 65 public int FontStyle { get; set; } 66 67 /// <summary> 68 /// 是否设置字体阴影 69 /// </summary> 70 [CategoryAttribute("文字水印"), Description("是否设置字体阴影")] 71 public bool IsSetBadge { get; set; } 72 73 /// <summary> 74 /// 横向偏移量 75 /// </summary> 76 [CategoryAttribute("文字水印"), Description("横向偏移量,设置背景阴影的横向偏移量,设置为负数为左偏移,正数为右偏移,只有在开启阴影效果后才有效果")] 77 public int OffsetU { get; set; } 78 79 /// <summary> 80 /// 纵向偏移量 81 /// </summary> 82 [CategoryAttribute("文字水印"), Description("纵向偏移量,设置背景阴影的横向偏移量,设置为负数为上偏移,正数为下偏移,只有在开启阴影效果后才有效果")] 83 84 public int OffsetV { get; set; } 85 86 /// <summary> 87 /// 阴影颜色 88 /// </summary> 89 [CategoryAttribute("文字水印"), Description("阴影颜色")] 90 public string ShadowColor { get; set; } 91 92 /// <summary> 93 /// 阴影大小 94 /// </summary> 95 [CategoryAttribute("文字水印"), Description("阴影大小,设置阴影的大小,只有在开启阴影效果后才有效果")] 96 public int ShadowSize { get; set; } 97 98 [CategoryAttribute("文字水印"), Description("字体边框大小")] 99 public int FontBroderSize { get; set; } 100 101 [CategoryAttribute("文字水印"), Description("字体边框颜色")] 102 public string FontBroderColor { get; set; } 103 #endregion 104 105 #region 图片水印 106 /// <summary> 107 /// 水印图片地址 108 /// </summary> 109 [CategoryAttribute("图片水印"), Description("水印图片地址")] 110 public string WatermarkImagePath { get; set; } 111 112 /// <summary> 113 /// 不透明度(最高可设置为10) 114 /// </summary> 115 [CategoryAttribute("图片水印"), Description("不透明度")] 116 public Single Opacity { get; set; } 117 #endregion 118 119 /// <summary> 120 /// 水印位置 121 /// </summary> 122 [CategoryAttribute("常用"), Description("水印标注位置,{1:'中间',2:'中上',3:'中下',4:'左上',5:'左下',6:'右上',7:'右下',8:'随机',9:'自定义'}")] 123 public int Position { get; set; } 124 125 [CategoryAttribute("常用"), Description("偏移量,当设置非自定义标注位置时,可设置偏移量进行适当的调整")] 126 public float Offset { get; set; } 127 128 /// <summary> 129 /// 水印坐标位置:X 130 /// </summary> 131 [CategoryAttribute("常用"), Description("水印坐标位置X:设置水印图片显示坐标,只有在水印位置标注为自定义时才有效")] 132 public float X { get; set; } 133 134 /// <summary> 135 /// 水印坐标位置:Y 136 /// </summary> 137 [CategoryAttribute("常用"), Description("水印坐标位置Y:设置水印图片显示坐标,只有在水印位置标注为自定义时才有效")] 138 139 public float Y { get; set; } 140 141 /// <summary> 142 /// 水印质量(最高可设置为100) 143 /// </summary> 144 [CategoryAttribute("常用"), Description("水印质量")] 145 public int Quality { get; set; } 146 147 /// <summary> 148 /// 水印图片存放路径 149 /// </summary> 150 [CategoryAttribute("常用"), Description("水印图片存放路径,即最后生成的水印图片存放的路径")] 151 public string WaterMarkSavePath { get; set; } 152 153 }
水印处理类:

1 /// <summary> 2 /// 水印处理类 3 /// </summary> 4 public class WaterMark 5 { 6 private WaterMarkConfig config = null; 7 public Image sourceImg; 8 private byte[] imgBuffer; 9 10 /// <summary> 11 /// 构造函数 12 /// </summary> 13 /// <param name="filePath">源文件路径</param> 14 /// <param name="outputPath">水印文件保存路径</param> 15 /// <param name="config">水印配置信息</param> 16 public WaterMark(string sourceFilePath, string outputPath, WaterMarkConfig config) 17 { 18 this.SourceImgPath = sourceFilePath; 19 this.FileSavePath = outputPath; 20 this.Config = config; 21 } 22 23 public WaterMark(byte[] buffer, string outputPath, WaterMarkConfig config) 24 { 25 imgBuffer = buffer; 26 this.FileSavePath = outputPath; 27 this.Config = config; 28 } 29 30 /// <summary> 31 /// 水印配置信息 32 /// </summary> 33 public WaterMarkConfig Config 34 { 35 get 36 { 37 return config; 38 } 39 set 40 { 41 config = value; 42 } 43 } 44 45 /// <summary> 46 /// 原图片路径 47 /// </summary> 48 public string SourceImgPath { get; set; } 49 50 /// <summary> 51 /// 文件保存路径 52 /// </summary> 53 public string FileSavePath { get; set; } 54 55 #region 制作水印 56 /// <summary> 57 /// 制作水印 58 /// </summary> 59 public void MakeWaterMark() 60 { 61 MakeWaterMark(false); 62 } 63 64 /// <summary> 65 /// 制作水印 66 /// </summary> 67 /// <param name="isPreview">是否为预览状态</param> 68 private void MakeWaterMark(bool isPreview) 69 { 70 if (null == Config) 71 { 72 return; 73 } 74 //判断是否开启水印功能 75 if (Config.IsEnableWatermark == false) 76 { 77 return; 78 } 79 80 if (string.IsNullOrEmpty(this.SourceImgPath) || !File.Exists(this.SourceImgPath)) 81 { 82 if (imgBuffer != null) 83 { 84 this.sourceImg = ImageDealHelper.StreamToImage(imgBuffer); 85 } 86 } 87 else 88 { 89 this.sourceImg = Image.FromFile(this.SourceImgPath); 90 } 91 92 if (!isPreview) 93 { 94 string fileExtention = Path.GetExtension(this.SourceImgPath); 95 this.FileSavePath = GetFileSavePath(this.FileSavePath, fileExtention); 96 } 97 98 if ((WatermarkType)config.Type == WatermarkType.Image) 99 { 100 this.sourceImg = MakeImageWaterMark(isPreview); 101 } 102 else 103 { 104 this.sourceImg = MakeTextWaterMark(isPreview); 105 } 106 if (null == this.sourceImg) 107 { 108 return; 109 } 110 //设置是生成质量 111 ImageCodecInfo ici = null; 112 EncoderParameters ep = null; 113 SetQuality(ref ici, ref ep, Config.Quality); 114 115 if (ici != null && isPreview == true) 116 { 117 MemoryStream ms = new MemoryStream(); 118 this.sourceImg.Save(ms, this.sourceImg.RawFormat); 119 imgBuffer = ms.GetBuffer(); 120 } 121 else 122 { 123 this.sourceImg.Save(this.FileSavePath, ici, ep); 124 } 125 this.sourceImg.Dispose(); 126 //if (!isPreview) 127 //{ 128 // File.Delete(this.SourceImgPath); //生成水印图后,将原图删除 129 //} 130 } 131 #endregion 132 133 #region 文字水印 134 /// <summary> 135 /// 文字水印 136 /// </summary> 137 /// <param name="image"></param> 138 /// <returns></returns> 139 private Image MakeTextWaterMark(bool isPreview) 140 { 141 Graphics g = Graphics.FromImage(this.sourceImg); 142 143 //设置质量 144 g.InterpolationMode = InterpolationMode.High; 145 g.SmoothingMode = SmoothingMode.HighQuality; 146 FontStyle fontStyle = (FontStyle)Config.FontStyle; 147 Font font = new Font(Config.FontFamily, Config.FontSize, fontStyle); 148 149 //设置位置 150 SizeF imageSize = new SizeF(this.sourceImg.Width, this.sourceImg.Height); 151 SizeF watermarkSize = g.MeasureString(Config.Text, font); 152 PointF point = CalculationPoint(imageSize, watermarkSize); 153 154 if (this.sourceImg.RawFormat.Guid == ImageFormat.Gif.Guid) 155 { 156 if (this.sourceImg != null) 157 { 158 this.sourceImg.Dispose(); 159 g.Dispose(); 160 } 161 if (imgBuffer != null) 162 { 163 imgBuffer = GifHelper.SmartWaterMark(imgBuffer, Config.Text, ColorTranslator.FromHtml(Config.FontColor), font, point, this.FileSavePath, isPreview); 164 } 165 else 166 { 167 imgBuffer = GifHelper.SmartWaterMark(this.SourceImgPath, Config.Text, ColorTranslator.FromHtml(Config.FontColor), font, point, this.FileSavePath, isPreview); 168 } 169 return null; 170 } 171 172 //设置边框 173 if (Config.FontBroderSize > 0) 174 { 175 SetBorder(g, point, watermarkSize); 176 } 177 178 //设置文字阴影 179 if (Config.IsSetBadge) 180 { 181 SetBadge(this.sourceImg, font, point, watermarkSize); 182 } 183 g.DrawString(Config.Text, font, new SolidBrush(ColorTranslator.FromHtml(Config.FontColor)), point); 184 g.Dispose(); 185 return this.sourceImg; 186 } 187 #endregion 188 189 #region 制作图片水印 190 /// <summary> 191 /// 制作图片水印 192 /// </summary> 193 /// <param name="SourceImg"></param> 194 /// <returns></returns> 195 private Image MakeImageWaterMark(bool isPreview) 196 { 197 Graphics g = Graphics.FromImage(sourceImg); 198 199 //设置质量 200 g.InterpolationMode = InterpolationMode.High; 201 g.SmoothingMode = SmoothingMode.HighQuality; 202 203 string waterImgPath = Path.GetFullPath(Config.WatermarkImagePath); 204 //判断当前水印图片是否存在 205 if (string.IsNullOrEmpty(waterImgPath) || !File.Exists(waterImgPath)) 206 { 207 return null; 208 } 209 Bitmap watermarkImg = new Bitmap(waterImgPath); 210 //透明属性 211 float opacity = Config.Opacity / 100.0F; 212 ImageAttributes imageAttr = GetOpacityAttribute(opacity); 213 214 //设置位置 215 SizeF imageSize = new SizeF(sourceImg.Width, sourceImg.Height); 216 SizeF watermarkSize = new SizeF(watermarkImg.Width, watermarkImg.Height); 217 PointF point = CalculationPoint(imageSize, watermarkSize); 218 Rectangle rec = new Rectangle((int)point.X, (int)point.Y, (int)watermarkSize.Width, (int)watermarkSize.Height); 219 if (this.sourceImg.RawFormat == ImageFormat.Gif) 220 { 221 this.sourceImg.Dispose(); 222 g.Dispose(); 223 imgBuffer = GifHelper.WaterMark(this.SourceImgPath, watermarkImg, rec, watermarkSize, imageAttr, this.FileSavePath, isPreview); 224 return null; 225 } 226 227 g.DrawImage(watermarkImg, rec, 0, 0, watermarkImg.Width, watermarkImg.Height, GraphicsUnit.Pixel, imageAttr); 228 watermarkImg.Dispose(); 229 return sourceImg; 230 } 231 #endregion 232 233 #region 设置边框 234 /// <summary> 235 /// 设置边框 236 /// </summary> 237 /// <param name="g"></param> 238 /// <param name="point"></param> 239 /// <param name="watermarkSize"></param> 240 public void SetBorder(Graphics g, PointF point, SizeF watermarkSize) 241 { 242 SolidBrush solid = new SolidBrush(ColorTranslator.FromHtml(Config.FontBroderColor)); 243 int fontWidth = Config.FontBroderSize; 244 Pen pen = new Pen(solid, fontWidth); 245 int x = (int)point.X; 246 int y = (int)point.Y; 247 int width = (int)(watermarkSize.Width); 248 int height = (int)(watermarkSize.Height); 249 int text = fontWidth / 2; 250 g.DrawLine(pen, new Point(x - fontWidth, y - text), new Point((int)(x + fontWidth + width), y - text)); 251 g.DrawLine(pen, new Point(x - text, y - text), new Point((int)(x - text), y + height + text)); 252 g.DrawLine(pen, new Point(x - fontWidth, y + text + height), new Point((int)(x + fontWidth + width), y + text + height)); 253 g.DrawLine(pen, new Point(x + text + width, y - text), new Point((int)(x + text + width), y + height + text)); 254 } 255 #endregion 256 257 #region 获得和设置透明属性 258 /// <summary> 259 /// 获得和设置透明属性 260 /// </summary> 261 /// <param name="opacity"></param> 262 /// <returns></returns> 263 public ImageAttributes GetOpacityAttribute(float opacity) 264 { 265 ImageAttributes imgAttributes = new ImageAttributes(); 266 ColorMap colorMap = new ColorMap(); 267 colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); 268 colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); 269 ColorMap[] remapTable = { colorMap }; 270 imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); 271 272 float[][] colorMatrixElements = { 273 new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, 274 new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, 275 new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, 276 new float[] {0.0f, 0.0f, 0.0f, opacity, 0.0f}, 277 new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f} 278 }; 279 280 ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); 281 imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); 282 return imgAttributes; 283 } 284 #endregion 285 286 #region 设置文字的阴影 287 /// <summary> 288 /// 设置文字的阴影 289 /// </summary> 290 /// <param name="Pict"></param> 291 /// <param name="Str"></param> 292 /// <param name="font"></param> 293 /// <param name="pointf"></param> 294 /// <returns></returns> 295 private Image SetBadge(Image image, Font font, PointF pointf, SizeF watermarkSize) 296 { 297 String str = Config.Text; 298 int fontSize = (int)font.Size; 299 FontStyle fontStyle = (FontStyle)Config.FontStyle; 300 //bool isSetFont = false; //当前水印文字大小是否超过图片大小 301 int imageWidth = image.Width; 302 int imageHeight = image.Height; 303 int Var_StrX = (int)pointf.X; 304 int Var_StrY = (int)pointf.Y; 305 Color foreColor = ColorTranslator.FromHtml(Config.ShadowColor); 306 307 Bitmap Var_bmp = new Bitmap(imageWidth, imageHeight); 308 Bitmap Var_SaveBmp = new Bitmap(image); 309 Graphics g = Graphics.FromImage(Var_bmp); 310 Graphics tem_Graphics = Graphics.FromImage(image); 311 SizeF Var_Size = new SizeF(imageWidth, imageHeight); 312 g.Clear(Color.Transparent); 313 314 g.DrawString(str, font, new SolidBrush(foreColor), Var_StrX, Var_StrY); 315 int tem_Become = 100; 316 for (int x = 1; x < Var_bmp.Width; x++) 317 { 318 for (int y = 1; y < Var_bmp.Height; y++) 319 { 320 int tem_a, tem_r, tem_g, tem_b, tem_r1, tem_g1, tem_b1; 321 if (Var_bmp.GetPixel(x, y).ToArgb() == foreColor.ToArgb() 322 || foreColor == ColorTranslator.FromHtml(Config.FontColor)) 323 { 324 tem_a = Var_SaveBmp.GetPixel(x, y).A; 325 tem_r = Var_SaveBmp.GetPixel(x, y).R; 326 tem_g = Var_SaveBmp.GetPixel(x, y).G; 327 tem_b = Var_SaveBmp.GetPixel(x, y).B; 328 tem_r1 = tem_r; 329 tem_g1 = tem_g; 330 tem_b1 = tem_b; 331 332 if (tem_b + tem_Become < 255) 333 tem_b = tem_b + 255; 334 if (tem_g + tem_Become < 255) 335 tem_g = tem_g + 255; 336 if (tem_r + tem_Become < 255) 337 tem_r = tem_r + 255; 338 if (tem_r1 - tem_Become > 0) 339 tem_r1 = tem_r1 - tem_Become; 340 if (tem_g1 - tem_Become > 0) 341 tem_g1 = tem_g1 - tem_Become; 342 if (tem_b1 - tem_Become > 0) 343 tem_b1 = tem_b1 - tem_Become; 344 tem_Graphics.DrawEllipse(new Pen(new SolidBrush(foreColor)), x + Config.OffsetU, y + Config.OffsetV, Config.ShadowSize, Config.ShadowSize);//绘制文字的阴影 345 tem_Graphics.DrawEllipse(new Pen(new SolidBrush(Color.FromArgb(tem_a, tem_r1, tem_g1, tem_b1))), x, y, 1, 1); 346 } 347 } 348 } 349 return image; 350 } 351 #endregion 352 353 #region 设置生成质量 354 /// <summary> 355 /// 设置生成质量 356 /// </summary> 357 /// <param name="ici"></param> 358 /// <param name="ep"></param> 359 /// <param name="quality"></param> 360 public void SetQuality(ref ImageCodecInfo ici, ref EncoderParameters ep, long quality) 361 { 362 ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); 363 foreach (ImageCodecInfo i in icis) 364 { 365 if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") 366 { 367 ici = i; 368 } 369 } 370 long[] qualityParam = new long[1]; 371 qualityParam[0] = quality; 372 ep = new EncoderParameters(1); 373 ep.Param[0] = new EncoderParameter(Encoder.Quality, qualityParam); 374 } 375 #endregion 376 377 #region 获得显示坐标 378 /// <summary> 379 /// 获得显示坐标 380 /// </summary> 381 /// <returns></returns> 382 private PointF CalculationPoint(SizeF ImageSize, SizeF watermarkSize) 383 { 384 PointF pointf = new PointF(); 385 if ((WatermarkPosition)Config.Position == WatermarkPosition.Manual) 386 { 387 pointf.X = Config.X; 388 pointf.Y = Config.Y; 389 return pointf; 390 } 391 392 float width = ImageSize.Width; 393 float height = ImageSize.Height; 394 float waterMarkWidth = watermarkSize.Width; 395 float waterMarkHeight = watermarkSize.Height; 396 WatermarkPosition position = (WatermarkPosition)Config.Position; 397 398 switch (position) 399 { 400 case WatermarkPosition.Center: 401 pointf.X = (width - waterMarkWidth) / 2; 402 pointf.Y = (height - waterMarkHeight) / 2; 403 break; 404 case WatermarkPosition.CenterDown: 405 pointf.X = (width - waterMarkWidth) / 2; 406 pointf.Y = (height - waterMarkHeight); 407 break; 408 case WatermarkPosition.CenterUp: 409 pointf.X = (width - waterMarkWidth) / 2; 410 pointf.Y = 0; 411 break; 412 case WatermarkPosition.LeftDown: 413 pointf.X = 0; 414 pointf.Y = (height - waterMarkHeight) / 2; 415 break; 416 case WatermarkPosition.LeftUp: 417 pointf.X = 0; 418 pointf.Y = 0; 419 break; 420 case WatermarkPosition.Random: 421 Random random = new Random(); 422 int x = random.Next(0, (int)width); 423 int y = random.Next(0, (int)height); 424 pointf.X = x > (width - waterMarkWidth) / 2 ? (width - waterMarkWidth) / 2 : x; 425 pointf.Y = y > ((height - waterMarkHeight) / 2) ? (height - waterMarkHeight) / 2 : y; 426 break; 427 case WatermarkPosition.RightDown: 428 pointf.X = width - waterMarkWidth; 429 pointf.Y = height - waterMarkHeight; 430 break; 431 case WatermarkPosition.RightUp: 432 pointf.X = width - waterMarkWidth; 433 pointf.Y = 0; 434 break; 435 } 436 437 float offset = Config.Offset; 438 pointf.X = pointf.X + offset; 439 pointf.Y = pointf.Y + offset; 440 return pointf; 441 } 442 #endregion 443 444 #region 获得文件流 445 /// <summary> 446 /// 获得添加水印后的文件流 447 /// </summary> 448 /// <returns></returns> 449 public byte[] GetWatermarkStream(string sourceFilePath) 450 { 451 MakeWaterMark(true); 452 if (imgBuffer != null) 453 { 454 return imgBuffer; 455 } 456 return null; 457 } 458 459 /// <summary> 460 /// 获得添加水印后的文件流 461 /// </summary> 462 /// <param name="buffer"></param> 463 /// <returns></returns> 464 public byte[] GetWatermarkStream(byte[] buffer) 465 { 466 this.imgBuffer = buffer; 467 MakeWaterMark(true); 468 if (imgBuffer != null) 469 { 470 return imgBuffer; 471 } 472 return null; 473 } 474 #endregion 475 476 #region 获得保存路径 477 /// <summary> 478 ///获得保存路径 (指定的保存路径->配置文件中的保存路径->默认保存路径) 479 /// </summary> 480 /// <param name="outputPath">指定的保存路径</param> 481 /// <param name="fileExtention">文件后缀</param> 482 /// <returns></returns> 483 public string GetFileSavePath(string outputPath, string fileExtention) 484 { 485 string filePath = null; 486 if (!string.IsNullOrEmpty(outputPath)) 487 { 488 filePath = string.Concat(outputPath, "_", Path.GetFileName(this.SourceImgPath)); 489 } 490 else 491 { 492 string fileName = Path.GetFileName(this.SourceImgPath); 493 if (string.IsNullOrEmpty(Config.WaterMarkSavePath)) 494 { 495 string path = string.Concat(Path.GetDirectoryName(this.SourceImgPath), "\\_", fileName); 496 filePath = path; 497 } 498 else 499 { 500 filePath = Path.GetFullPath(string.Concat(Config.WaterMarkSavePath, "_", fileName)); 501 } 502 } 503 return filePath; 504 } 505 #endregion 506 507 }
图片处理类:

1 /// <summary> 2 /// 图片处理类 3 /// </summary> 4 public class ImageDealHelper 5 { 6 7 #region 水印处理 8 /// <summary> 9 /// 设置水印(水印图片路径根据配置信息中的水印保存路径保存) 10 /// 当配置信息中水印保存路径不存在时,在源文件当前目录下保存 11 /// </summary> 12 /// <param name="filePath">源文件路径</param> 13 public static string MakeWaterMark(string fileSourcePath) 14 { 15 return MakeWaterMark(fileSourcePath, null); 16 } 17 18 /// <summary> 19 /// 保存图片 20 /// </summary> 21 /// <param name="fileSourcePath">源文件路径</param> 22 /// <param name="outputPath">水印文件保存路径</param> 23 /// <returns></returns> 24 public static string MakeWaterMark(string fileSourcePath, string outputPath) 25 { 26 return MakeWaterMark(fileSourcePath, outputPath, WaterMarkConfig.Instance); 27 } 28 29 /// <summary> 30 /// 保存图片 31 /// </summary> 32 /// <param name="fileSourcePath">源文件路径</param> 33 /// <param name="outputPath">水印文件保存路径</param> 34 /// <param name="config"></param> 35 /// <returns></returns> 36 public static string MakeWaterMark(string fileSourcePath, string outputPath, WaterMarkConfig config) 37 { 38 WaterMark watermark = new WaterMark(fileSourcePath, outputPath, config); 39 watermark.MakeWaterMark(); 40 return watermark.FileSavePath; 41 } 42 43 /// <summary> 44 /// 预览水印图片 45 /// </summary> 46 /// <returns></returns> 47 public static byte[] WatermarkPreview(string fileSourcePath) 48 { 49 WaterMark watermark = new WaterMark(fileSourcePath, null, WaterMarkConfig.Instance); 50 return watermark.GetWatermarkStream(fileSourcePath); 51 } 52 53 /// <summary> 54 /// 预览水印图片 55 /// </summary> 56 /// <param name="buffer"></param> 57 /// <returns></returns> 58 public static byte[] WatermarkPreview(byte[] buffer) 59 { 60 WaterMark watermark = new WaterMark(buffer, null, WaterMarkConfig.Instance); 61 return watermark.GetWatermarkStream(buffer); 62 } 63 #endregion 64 65 #region 判断文件类型是否为WEB格式图片 66 /// <summary> 67 /// 判断文件类型是否为WEB格式图片 68 /// (注:JPG,GIF,BMP,PNG) 69 /// </summary> 70 /// <param name="extention">HttpPostedFile.ContentType</param> 71 /// <returns></returns> 72 internal static bool IsWebImage(string extention) 73 { 74 extention = extention.ToLower(); 75 if (extention == ".jpeg" || extention == ".jpeg" || extention == ".gif" || extention == ".bmp" || extention == ".png") 76 { 77 return true; 78 } 79 else 80 { 81 return false; 82 } 83 } 84 #endregion 85 86 #region 根据后缀返回相应图片格式类型 87 /// <summary> 88 /// 根据后缀返回相应图片格式类型 89 /// </summary> 90 /// <param name="extention"></param> 91 /// <returns></returns> 92 public static ImageFormat GetImageFormart(string extention) 93 { 94 if (string.IsNullOrEmpty(extention)) 95 { 96 return null; 97 } 98 extention = extention.ToLower(); 99 ImageFormat imgFormart = default(ImageFormat); 100 switch (extention) 101 { 102 case ".jpeg": 103 imgFormart = ImageFormat.Jpeg; 104 break; 105 case ".gif": 106 imgFormart = ImageFormat.Gif; 107 break; 108 case ".bmp": 109 imgFormart = ImageFormat.Bmp; 110 break; 111 case "png": 112 imgFormart = ImageFormat.Png; 113 break; 114 default: imgFormart = ImageFormat.Jpeg; 115 break; 116 } 117 return imgFormart; 118 } 119 #endregion 120 121 #region 图片转化为流 122 /// <summary> 123 /// 图片转化为流 124 /// </summary> 125 /// <param name="img"></param> 126 /// <param name="extention"></param> 127 /// <returns></returns> 128 public static byte[] ImageToStream(Image img, ImageFormat imgFormart) 129 { 130 MemoryStream ms = new MemoryStream(); 131 img.Save(ms, imgFormart); 132 return ms.GetBuffer(); 133 } 134 135 #endregion 136 137 #region 流转化为图片 138 /// <summary> 139 /// 流转化为图片 140 /// </summary> 141 /// <param name="buffer"></param> 142 /// <returns></returns> 143 public static Image StreamToImage(byte[] buffer) 144 { 145 MemoryStream ms = new MemoryStream(buffer); 146 return Image.FromStream(ms); 147 } 148 #endregion 149 150 #region 根据URL返回文件二进制流 151 /// <summary> 152 /// 根据URL返回文件二进制流 153 /// </summary> 154 /// <param name="url"></param> 155 /// <returns></returns> 156 public static byte[] URLToStream(string url) 157 { 158 WebRequest request = WebRequest.Create(url); 159 WebResponse response = request.GetResponse(); 160 Stream stream = response.GetResponseStream(); 161 Image img = Image.FromStream(stream); 162 byte[] buffer = ImageToStream(img, img.RawFormat); 163 return buffer; 164 } 165 #endregion 166 }
源码下载:点击下载