最全的C#图片处理帮助类ImageHelper

最全的C#图片处理帮助类ImageHelper.cs

方法介绍:

  • 生成缩略图
  • 图片水印处理方法
  • 图片水印位置处理方法
  • 文字水印处理方法
  • 文字水印位置的方法
  • 调整光暗
  • 反色处理
  • 浮雕处理
  • 拉伸图片
  • 滤色处理
  •  左右翻转
  • 上下翻转
  • 压缩到指定尺寸
  • 转换为黑白图片
  • 获取图片中的各帧

资源下载列表

  1 using System;
  2 using System.Collections;
  3 using System.IO;
  4 using System.Drawing;
  5 using System.Drawing.Imaging;
  6 using System.Drawing.Drawing2D;
  7 
  8 namespace HelloCsharp.Utilities
  9 {
 10     public class ImageClass
 11     {
 12         public ImageClass()
 13         { }
 14 
 15         #region 缩略图
 16         /// <summary>
 17         /// 生成缩略图
 18         /// </summary>
 19         /// <param name="originalImagePath">源图路径(物理路径)</param>
 20         /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
 21         /// <param name="width">缩略图宽度</param>
 22         /// <param name="height">缩略图高度</param>
 23         /// <param name="mode">生成缩略图的方式</param>    
 24         public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
 25         {
 26             System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
 27 
 28             int towidth = width;
 29             int toheight = height;
 30 
 31             int x = 0;
 32             int y = 0;
 33             int ow = originalImage.Width;
 34             int oh = originalImage.Height;
 35 
 36             switch (mode)
 37             {
 38                 case "HW"//指定高宽缩放(可能变形)                
 39                     break;
 40                 case "W":   //指定宽,高按比例                    
 41                     toheight = originalImage.Height * width / originalImage.Width;
 42                     break;
 43                 case "H":   //指定高,宽按比例
 44                     towidth = originalImage.Width * height / originalImage.Height;
 45                     break;
 46                 case "Cut": //指定高宽裁减(不变形)                
 47                     if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
 48                     {
 49                         oh = originalImage.Height;
 50                         ow = originalImage.Height * towidth / toheight;
 51                         y = 0;
 52                         x = (originalImage.Width - ow) / 2;
 53                     }
 54                     else
 55                     {
 56                         ow = originalImage.Width;
 57                         oh = originalImage.Width * height / towidth;
 58                         x = 0;
 59                         y = (originalImage.Height - oh) / 2;
 60                     }
 61                     break;
 62                 default:
 63                     break;
 64             }
 65 
 66             //新建一个bmp图片
 67             System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
 68 
 69             //新建一个画板
 70             System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
 71 
 72             //设置高质量插值法
 73             g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
 74 
 75             //设置高质量,低速度呈现平滑程度
 76             g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
 77 
 78             //清空画布并以透明背景色填充
 79             g.Clear(System.Drawing.Color.Transparent);
 80 
 81             //在指定位置并且按指定大小绘制原图片的指定部分
 82             g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
 83 
 84             try
 85             {
 86                 //以jpg格式保存缩略图
 87                 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
 88             }
 89             catch (System.Exception e)
 90             {
 91                 throw e;
 92             }
 93             finally
 94             {
 95                 originalImage.Dispose();
 96                 bitmap.Dispose();
 97                 g.Dispose();
 98             }
 99         }
100         #endregion
101 
102         #region 图片水印
103         /// <summary>
104         /// 图片水印处理方法
105         /// </summary>
106         /// <param name="path">需要加载水印的图片路径(绝对路径)</param>
107         /// <param name="waterpath">水印图片(绝对路径)</param>
108         /// <param name="location">水印位置(传送正确的代码)</param>
109         public static string ImageWatermark(string path, string waterpath, string location)
110         {
111             string kz_name = Path.GetExtension(path);
112             if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg")
113             {
114                 DateTime time = DateTime.Now;
115                 string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString();
116                 Image img = Bitmap.FromFile(path);
117                 Image waterimg = Image.FromFile(waterpath);
118                 Graphics g = Graphics.FromImage(img);
119                 ArrayList loca = GetLocation(location, img, waterimg);
120                 g.DrawImage(waterimg, new Rectangle(int.Parse(loca[0].ToString()), int.Parse(loca[1].ToString()), waterimg.Width, waterimg.Height));
121                 waterimg.Dispose();
122                 g.Dispose();
123                 string newpath = Path.GetDirectoryName(path) + filename + kz_name;
124                 img.Save(newpath);
125                 img.Dispose();
126                 File.Copy(newpath, path, true);
127                 if (File.Exists(newpath))
128                 {
129                     File.Delete(newpath);
130                 }
131             }
132             return path;
133         }
134 
135         /// <summary>
136         /// 图片水印位置处理方法
137         /// </summary>
138         /// <param name="location">水印位置</param>
139         /// <param name="img">需要添加水印的图片</param>
140         /// <param name="waterimg">水印图片</param>
141         private static ArrayList GetLocation(string location, Image img, Image waterimg)
142         {
143             ArrayList loca = new ArrayList();
144             int x = 0;
145             int y = 0;
146 
147             if (location == "LT")
148             {
149                 x = 10;
150                 y = 10;
151             }
152             else if (location == "T")
153             {
154                 x = img.Width / 2 - waterimg.Width / 2;
155                 y = img.Height - waterimg.Height;
156             }
157             else if (location == "RT")
158             {
159                 x = img.Width - waterimg.Width;
160                 y = 10;
161             }
162             else if (location == "LC")
163             {
164                 x = 10;
165                 y = img.Height / 2 - waterimg.Height / 2;
166             }
167             else if (location == "C")
168             {
169                 x = img.Width / 2 - waterimg.Width / 2;
170                 y = img.Height / 2 - waterimg.Height / 2;
171             }
172             else if (location == "RC")
173             {
174                 x = img.Width - waterimg.Width;
175                 y = img.Height / 2 - waterimg.Height / 2;
176             }
177             else if (location == "LB")
178             {
179                 x = 10;
180                 y = img.Height - waterimg.Height;
181             }
182             else if (location == "B")
183             {
184                 x = img.Width / 2 - waterimg.Width / 2;
185                 y = img.Height - waterimg.Height;
186             }
187             else
188             {
189                 x = img.Width - waterimg.Width;
190                 y = img.Height - waterimg.Height;
191             }
192             loca.Add(x);
193             loca.Add(y);
194             return loca;
195         }
196         #endregion
197 
198         #region 文字水印
199         /// <summary>
200         /// 文字水印处理方法
201         /// </summary>
202         /// <param name="path">图片路径(绝对路径)</param>
203         /// <param name="size">字体大小</param>
204         /// <param name="letter">水印文字</param>
205         /// <param name="color">颜色</param>
206         /// <param name="location">水印位置</param>
207         public static string LetterWatermark(string path, int size, string letter, Color color, string location)
208         {
209             #region
210 
211             string kz_name = Path.GetExtension(path);
212             if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg")
213             {
214                 DateTime time = DateTime.Now;
215                 string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString();
216                 Image img = Bitmap.FromFile(path);
217                 Graphics gs = Graphics.FromImage(img);
218                 ArrayList loca = GetLocation(location, img, size, letter.Length);
219                 Font font = new Font("宋体", size);
220                 Brush br = new SolidBrush(color);
221                 gs.DrawString(letter, font, br, float.Parse(loca[0].ToString()), float.Parse(loca[1].ToString()));
222                 gs.Dispose();
223                 string newpath = Path.GetDirectoryName(path) + filename + kz_name;
224                 img.Save(newpath);
225                 img.Dispose();
226                 File.Copy(newpath, path, true);
227                 if (File.Exists(newpath))
228                 {
229                     File.Delete(newpath);
230                 }
231             }
232             return path;
233 
234             #endregion
235         }
236 
237         /// <summary>
238         /// 文字水印位置的方法
239         /// </summary>
240         /// <param name="location">位置代码</param>
241         /// <param name="img">图片对象</param>
242         /// <param name="width">宽(当水印类型为文字时,传过来的就是字体的大小)</param>
243         /// <param name="height">高(当水印类型为文字时,传过来的就是字符的长度)</param>
244         private static ArrayList GetLocation(string location, Image img, int width, int height)
245         {
246             #region
247 
248             ArrayList loca = new ArrayList();  //定义数组存储位置
249             float x = 10;
250             float y = 10;
251 
252             if (location == "LT")
253             {
254                 loca.Add(x);
255                 loca.Add(y);
256             }
257             else if (location == "T")
258             {
259                 x = img.Width / 2 - (width * height) / 2;
260                 loca.Add(x);
261                 loca.Add(y);
262             }
263             else if (location == "RT")
264             {
265                 x = img.Width - width * height;
266             }
267             else if (location == "LC")
268             {
269                 y = img.Height / 2;
270             }
271             else if (location == "C")
272             {
273                 x = img.Width / 2 - (width * height) / 2;
274                 y = img.Height / 2;
275             }
276             else if (location == "RC")
277             {
278                 x = img.Width - height;
279                 y = img.Height / 2;
280             }
281             else if (location == "LB")
282             {
283                 y = img.Height - width - 5;
284             }
285             else if (location == "B")
286             {
287                 x = img.Width / 2 - (width * height) / 2;
288                 y = img.Height - width - 5;
289             }
290             else
291             {
292                 x = img.Width - width * height;
293                 y = img.Height - width - 5;
294             }
295             loca.Add(x);
296             loca.Add(y);
297             return loca;
298 
299             #endregion
300         }
301         #endregion
302 
303         #region 调整光暗
304         /// <summary>
305         /// 调整光暗
306         /// </summary>
307         /// <param name="mybm">原始图片</param>
308         /// <param name="width">原始图片的长度</param>
309         /// <param name="height">原始图片的高度</param>
310         /// <param name="val">增加或减少的光暗值</param>
311         public Bitmap LDPic(Bitmap mybm, int width, int height, int val)
312         {
313             Bitmap bm = new Bitmap(width, height);//初始化一个记录经过处理后的图片对象
314             int x, y, resultR, resultG, resultB;//x、y是循环次数,后面三个是记录红绿蓝三个值的
315             Color pixel;
316             for (x = 0; x < width; x++)
317             {
318                 for (y = 0; y < height; y++)
319                 {
320                     pixel = mybm.GetPixel(x, y);//获取当前像素的值
321                     resultR = pixel.R + val;//检查红色值会不会超出[0, 255]
322                     resultG = pixel.G + val;//检查绿色值会不会超出[0, 255]
323                     resultB = pixel.B + val;//检查蓝色值会不会超出[0, 255]
324                     bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB));//绘图
325                 }
326             }
327             return bm;
328         }
329         #endregion
330 
331         #region 反色处理
332         /// <summary>
333         /// 反色处理
334         /// </summary>
335         /// <param name="mybm">原始图片</param>
336         /// <param name="width">原始图片的长度</param>
337         /// <param name="height">原始图片的高度</param>
338         public Bitmap RePic(Bitmap mybm, int width, int height)
339         {
340             Bitmap bm = new Bitmap(width, height);//初始化一个记录处理后的图片的对象
341             int x, y, resultR, resultG, resultB;
342             Color pixel;
343             for (x = 0; x < width; x++)
344             {
345                 for (y = 0; y < height; y++)
346                 {
347                     pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
348                     resultR = 255 - pixel.R;//反红
349                     resultG = 255 - pixel.G;//反绿
350                     resultB = 255 - pixel.B;//反蓝
351                     bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB));//绘图
352                 }
353             }
354             return bm;
355         }
356         #endregion
357 
358         #region 浮雕处理
359         /// <summary>
360         /// 浮雕处理
361         /// </summary>
362         /// <param name="oldBitmap">原始图片</param>
363         /// <param name="Width">原始图片的长度</param>
364         /// <param name="Height">原始图片的高度</param>
365         public Bitmap FD(Bitmap oldBitmap, int Width, int Height)
366         {
367             Bitmap newBitmap = new Bitmap(Width, Height);
368             Color color1, color2;
369             for (int x = 0; x < Width - 1; x++)
370             {
371                 for (int y = 0; y < Height - 1; y++)
372                 {
373                     int r = 0, g = 0, b = 0;
374                     color1 = oldBitmap.GetPixel(x, y);
375                     color2 = oldBitmap.GetPixel(x + 1, y + 1);
376                     r = Math.Abs(color1.R - color2.R + 128);
377                     g = Math.Abs(color1.G - color2.G + 128);
378                     b = Math.Abs(color1.B - color2.B + 128);
379                     if (r > 255) r = 255;
380                     if (r < 0) r = 0;
381                     if (g > 255) g = 255;
382                     if (g < 0) g = 0;
383                     if (b > 255) b = 255;
384                     if (b < 0) b = 0;
385                     newBitmap.SetPixel(x, y, Color.FromArgb(r, g, b));
386                 }
387             }
388             return newBitmap;
389         }
390         #endregion
391 
392         #region 拉伸图片
393         /// <summary>
394         /// 拉伸图片
395         /// </summary>
396         /// <param name="bmp">原始图片</param>
397         /// <param name="newW">新的宽度</param>
398         /// <param name="newH">新的高度</param>
399         public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH)
400         {
401             try
402             {
403                 Bitmap bap = new Bitmap(newW, newH);
404                 Graphics g = Graphics.FromImage(bap);
405                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
406                 g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
407                 g.Dispose();
408                 return bap;
409             }
410             catch
411             {
412                 return null;
413             }
414         }
415         #endregion
416 
417         #region 滤色处理
418         /// <summary>
419         /// 滤色处理
420         /// </summary>
421         /// <param name="mybm">原始图片</param>
422         /// <param name="width">原始图片的长度</param>
423         /// <param name="height">原始图片的高度</param>
424         public Bitmap FilPic(Bitmap mybm, int width, int height)
425         {
426             Bitmap bm = new Bitmap(width, height);//初始化一个记录滤色效果的图片对象
427             int x, y;
428             Color pixel;
429 
430             for (x = 0; x < width; x++)
431             {
432                 for (y = 0; y < height; y++)
433                 {
434                     pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
435                     bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B));//绘图
436                 }
437             }
438             return bm;
439         }
440         #endregion
441 
442         #region 左右翻转
443         /// <summary>
444         /// 左右翻转
445         /// </summary>
446         /// <param name="mybm">原始图片</param>
447         /// <param name="width">原始图片的长度</param>
448         /// <param name="height">原始图片的高度</param>
449         public Bitmap RevPicLR(Bitmap mybm, int width, int height)
450         {
451             Bitmap bm = new Bitmap(width, height);
452             int x, y, z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
453             Color pixel;
454             for (y = height - 1; y >= 0; y--)
455             {
456                 for (x = width - 1, z = 0; x >= 0; x--)
457                 {
458                     pixel = mybm.GetPixel(x, y);//获取当前像素的值
459                     bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B));//绘图
460                 }
461             }
462             return bm;
463         }
464         #endregion
465 
466         #region 上下翻转
467         /// <summary>
468         /// 上下翻转
469         /// </summary>
470         /// <param name="mybm">原始图片</param>
471         /// <param name="width">原始图片的长度</param>
472         /// <param name="height">原始图片的高度</param>
473         public Bitmap RevPicUD(Bitmap mybm, int width, int height)
474         {
475             Bitmap bm = new Bitmap(width, height);
476             int x, y, z;
477             Color pixel;
478             for (x = 0; x < width; x++)
479             {
480                 for (y = height - 1, z = 0; y >= 0; y--)
481                 {
482                     pixel = mybm.GetPixel(x, y);//获取当前像素的值
483                     bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B));//绘图
484                 }
485             }
486             return bm;
487         }
488         #endregion
489 
490         #region 压缩图片
491         /// <summary>
492         /// 压缩到指定尺寸
493         /// </summary>
494         /// <param name="oldfile">原文件</param>
495         /// <param name="newfile">新文件</param>
496         public bool Compress(string oldfile, string newfile)
497         {
498             try
499             {
500                 System.Drawing.Image img = System.Drawing.Image.FromFile(oldfile);
501                 System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;
502                 Size newSize = new Size(100, 125);
503                 Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
504                 Graphics g = Graphics.FromImage(outBmp);
505                 g.CompositingQuality = CompositingQuality.HighQuality;
506                 g.SmoothingMode = SmoothingMode.HighQuality;
507                 g.InterpolationMode = InterpolationMode.HighQualityBicubic;
508                 g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
509                 g.Dispose();
510                 EncoderParameters encoderParams = new EncoderParameters();
511                 long[] quality = new long[1];
512                 quality[0] = 100;
513                 EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
514                 encoderParams.Param[0] = encoderParam;
515                 ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
516                 ImageCodecInfo jpegICI = null;
517                 for (int x = 0; x < arrayICI.Length; x++)
518                     if (arrayICI[x].FormatDescription.Equals("JPEG"))
519                     {
520                         jpegICI = arrayICI[x]; //设置JPEG编码
521                         break;
522                     }
523                 img.Dispose();
524                 if (jpegICI != null) outBmp.Save(newfile, System.Drawing.Imaging.ImageFormat.Jpeg);
525                 outBmp.Dispose();
526                 return true;
527             }
528             catch
529             {
530                 return false;
531             }
532         }
533         #endregion
534 
535         #region 图片灰度化
536         public Color Gray(Color c)
537         {
538             int rgb = Convert.ToInt32((double)(((0.3 * c.R) + (0.59 * c.G)) + (0.11 * c.B)));
539             return Color.FromArgb(rgb, rgb, rgb);
540         }
541         #endregion
542 
543         #region 转换为黑白图片
544         /// <summary>
545         /// 转换为黑白图片
546         /// </summary>
547         /// <param name="mybt">要进行处理的图片</param>
548         /// <param name="width">图片的长度</param>
549         /// <param name="height">图片的高度</param>
550         public Bitmap BWPic(Bitmap mybm, int width, int height)
551         {
552             Bitmap bm = new Bitmap(width, height);
553             int x, y, result; //x,y是循环次数,result是记录处理后的像素值
554             Color pixel;
555             for (x = 0; x < width; x++)
556             {
557                 for (y = 0; y < height; y++)
558                 {
559                     pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
560                     result = (pixel.R + pixel.G + pixel.B) / 3;//取红绿蓝三色的平均值
561                     bm.SetPixel(x, y, Color.FromArgb(result, result, result));
562                 }
563             }
564             return bm;
565         }
566         #endregion
567 
568         #region 获取图片中的各帧
569         /// <summary>
570         /// 获取图片中的各帧
571         /// </summary>
572         /// <param name="pPath">图片路径</param>
573         /// <param name="pSavePath">保存路径</param>
574         public void GetFrames(string pPath, string pSavedPath)
575         {
576             Image gif = Image.FromFile(pPath);
577             FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]);
578             int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
579             for (int i = 0; i < count; i++)    //以Jpeg格式保存各帧
580             {
581                 gif.SelectActiveFrame(fd, i);
582                 gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
583             }
584         }
585         #endregion
586     }
587 }
View Code

 

posted @ 2015-11-24 16:20  Mr. Hu  阅读(7417)  评论(1编辑  收藏  举报
Map