2013年3月22日星期五

C#为图片添加水印,生成缩略图

文章引用自http://www.hackpig.cn/post/115.html,自己略微作了些修改
Java代码  收藏代码
  1. using System;  
  2. using System.IO;  
  3. using System.Collections;  
  4. using System.Drawing;  
  5. using System.Drawing.Drawing2D;  
  6. using System.Drawing.Imaging;  
  7.   
  8. namespace Imag_writer  
  9. {  
  10.     /// <summary>  
  11.     /// 水印的类型  
  12.     /// </summary>  
  13.     public enum WaterMarkType  
  14.     {  
  15.         /// <summary>  
  16.         /// 文字水印  
  17.         /// </summary>  
  18.         TextMark,  
  19.         /// <summary>  
  20.         /// 图片水印  
  21.         /// </summary>  
  22.         //ImageMark // 暂时只能添加文字水印  
  23.     };  
  24.   
  25.     /// <summary>  
  26.     /// 水印的位置  
  27.     /// </summary>  
  28.     public enum WaterMarkPosition  
  29.     {  
  30.         /// <summary>  
  31.         /// 左上角  
  32.         /// </summary>  
  33.         WMP_Left_Top,  
  34.         /// <summary>  
  35.         /// 左下角  
  36.         /// </summary>  
  37.         WMP_Left_Bottom,  
  38.         /// <summary>  
  39.         /// 右上角  
  40.         /// </summary>  
  41.         WMP_Right_Top,  
  42.         /// <summary>  
  43.         /// 右下角  
  44.         /// </summary>  
  45.         WMP_Right_Bottom  
  46.     };  
  47.   
  48.     /// <summary>  
  49.     /// 指定水印的位置  
  50.     /// </summary>  
  51.     public class Position  
  52.     {  
  53.         /// <summary>  
  54.         /// 左上角  
  55.         /// </summary>  
  56.         public string WM_TOP_LEFT = "WM_TOP_LEFT";  
  57.         /// <summary>  
  58.         /// 左下角  
  59.         /// </summary>  
  60.         public string WM_BOTTOM_LEFT = "WM_BOTTOM_LEFT";  
  61.         /// <summary>  
  62.         /// 右上角  
  63.         /// </summary>  
  64.         public string WM_TOP_RIGHT = "WM_TOP_RIGHT";  
  65.         /// <summary>  
  66.         /// 右下角  
  67.         /// </summary>  
  68.         public string WM_BOTTOM_RIGHT = "WM_BOTTOM_RIGHT";  
  69.   
  70.     }  
  71.   
  72.     /// <summary>  
  73.     /// 处理图片的类(包括加水印,生成缩略图)  
  74.     /// </summary>  
  75.     public class ImageWaterMark  
  76.     {  
  77.         public ImageWaterMark()  
  78.         {  
  79.             //  
  80.             // TODO: 在此处添加构造函数逻辑  
  81.             //  
  82.         }  
  83.   
  84.         #region 给图片加水印  
  85.         /// <summary>  
  86.         /// 添加水印(分图片水印与文字水印两种)  
  87.         /// </summary>  
  88.         /// <param name="oldpath">原图片绝对地址</param>  
  89.         /// <param name="newpath">新图片放置的绝对地址</param>  
  90.         /// <param name="wmtType">要添加的水印的类型</param>  
  91.         /// <param name="sWaterMarkContent">水印内容,若添加文字水印,此即为要添加的文字;  
  92.         /// 若要添加图片水印,此为图片的路径</param>  
  93.         public void addWaterMark(string oldpath, string newpath,  
  94.          WaterMarkType wmtType, string sWaterMarkContent, string position)  
  95.         {  
  96.             try  
  97.             {  
  98.                 Image image = Image.FromFile(oldpath);  
  99.   
  100.                 Bitmap b = new Bitmap(image.Width, image.Height,  
  101.                  PixelFormat.Format24bppRgb);  
  102.   
  103.                 Graphics g = Graphics.FromImage(b);  
  104.                 g.Clear(Color.White);  
  105.                 g.SmoothingMode = SmoothingMode.HighQuality;  
  106.                 g.InterpolationMode = InterpolationMode.High;  
  107.   
  108.                 g.DrawImage(image, 00, image.Width, image.Height);  
  109.   
  110.                 switch (wmtType)  
  111.                 {  
  112.   
  113.                     case WaterMarkType.TextMark:  
  114.                         //文字水印  
  115.                         //this.addWatermarkText(g, sWaterMarkContent, "WM_BOTTOM_RIGHT",  
  116.                         // image.Width, image.Height);  
  117.                         this.addWatermarkText(g, sWaterMarkContent, position,  
  118.                          image.Width, image.Height);  
  119.                         break;  
  120.                 }  
  121.   
  122.                 b.Save(newpath);  
  123.                 b.Dispose();  
  124.                 image.Dispose();  
  125.             }  
  126.             catch  
  127.             {  
  128.                 if (File.Exists(oldpath))  
  129.                 {  
  130.                     File.Delete(oldpath);  
  131.                 }  
  132.             }  
  133.             finally  
  134.             {  
  135.                 if (File.Exists(oldpath))  
  136.                 {  
  137.                     File.Delete(oldpath);  
  138.                 }  
  139.             }  
  140.         }  
  141.   
  142.         /// <summary>  
  143.         ///   加水印文字  
  144.         /// </summary>  
  145.         /// <param name="picture">imge 对象</param>  
  146.         /// <param name="_watermarkText">水印文字内容</param>  
  147.         /// <param name="_watermarkPosition">水印位置</param>  
  148.         /// <param name="_width">被加水印图片的宽</param>  
  149.         /// <param name="_height">被加水印图片的高</param>  
  150.         private void addWatermarkText(Graphics picture, string _watermarkText,  
  151.          string _watermarkPosition, int _width, int _height)  
  152.         {  
  153.             // 确定水印文字的字体大小  
  154.             int[] sizes = new int[] { 323028262422201816141210864 };  
  155.             Font crFont = null;  
  156.             SizeF crSize = new SizeF();  
  157.             for (int i = 0; i < sizes.Length; i++)  
  158.             {  
  159.                 crFont = new Font("Arial Black", sizes[i], FontStyle.Bold);  
  160.                 crSize = picture.MeasureString(_watermarkText, crFont);  
  161.   
  162.                 if ((ushort)crSize.Width < (ushort)_width)  
  163.                 {  
  164.                     break;  
  165.                 }  
  166.             }  
  167.   
  168.             // 生成水印图片(将文字写到图片中)  
  169.             Bitmap floatBmp = new Bitmap((int)crSize.Width + 3,  
  170.                   (int)crSize.Height + 3, PixelFormat.Format32bppArgb);  
  171.             Graphics fg = Graphics.FromImage(floatBmp);  
  172.             PointF pt = new PointF(00);  
  173.   
  174.             // 画阴影文字  
  175.             Brush TransparentBrush0 = new SolidBrush(Color.FromArgb(255, Color.Black));  
  176.             Brush TransparentBrush1 = new SolidBrush(Color.FromArgb(255, Color.Black));  
  177.             fg.DrawString(_watermarkText, crFont, TransparentBrush0, pt.X, pt.Y + 1);  
  178.             fg.DrawString(_watermarkText, crFont, TransparentBrush0, pt.X + 1, pt.Y);  
  179.   
  180.             fg.DrawString(_watermarkText, crFont, TransparentBrush1, pt.X + 1, pt.Y + 1);  
  181.             fg.DrawString(_watermarkText, crFont, TransparentBrush1, pt.X, pt.Y + 2);  
  182.             fg.DrawString(_watermarkText, crFont, TransparentBrush1, pt.X + 2, pt.Y);  
  183.   
  184.             TransparentBrush0.Dispose();  
  185.             TransparentBrush1.Dispose();  
  186.   
  187.             // 画文字  
  188.             fg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;  
  189.             fg.DrawString(_watermarkText,  
  190.              crFont, new SolidBrush(Color.White),  
  191.              pt.X, pt.Y, StringFormat.GenericDefault);  
  192.   
  193.             // 保存刚才的操作  
  194.             fg.Save();  
  195.             fg.Dispose();  
  196.             // floatBmp.Save("d:\WebSite\DIGITALKM\ttt.jpg");  
  197.   
  198.             // 将水印图片加到原图中  
  199.             this.addWatermarkImage(  
  200.              picture,  
  201.              new Bitmap(floatBmp),  
  202.              _watermarkPosition,//"WM_BOTTOM_RIGHT",  
  203.              _width,  
  204.              _height);  
  205.         }  
  206.   
  207.         /// <summary>  
  208.         ///   加水印图片  
  209.         /// </summary>  
  210.         /// <param name="picture">imge 对象</param>  
  211.         /// <param name="iTheImage">Image对象(以此图片为水印)</param>  
  212.         /// <param name="_watermarkPosition">水印位置</param>  
  213.         /// <param name="_width">被加水印图片的宽</param>  
  214.         /// <param name="_height">被加水印图片的高</param>  
  215.         private void addWatermarkImage(Graphics picture, Image iTheImage,  
  216.          string _watermarkPosition, int _width, int _height)  
  217.         {  
  218.             Image watermark = new Bitmap(iTheImage);  
  219.   
  220.             ImageAttributes imageAttributes = new ImageAttributes();  
  221.             ColorMap colorMap = new ColorMap();  
  222.   
  223.             colorMap.OldColor = Color.FromArgb(25502550);  
  224.             colorMap.NewColor = Color.FromArgb(0000);  
  225.             ColorMap[] remapTable = { colorMap };  
  226.   
  227.             imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);  
  228.   
  229.             float[][] colorMatrixElements = {  
  230.              new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},  
  231.              new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},  
  232.              new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},  
  233.              new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},  
  234.              new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}  
  235.             };  
  236.   
  237.             ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);  
  238.   
  239.             imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);  
  240.   
  241.             int xpos = 0;  
  242.             int ypos = 0;  
  243.             int WatermarkWidth = 0;  
  244.             int WatermarkHeight = 0;  
  245.             double bl = 1d;  
  246.   
  247.             //计算水印图片的比率  
  248.             //取背景的1/4宽度来比较  
  249.             if ((_width > watermark.Width * 4) && (_height > watermark.Height * 4))  
  250.             {  
  251.                 bl = 1;  
  252.             }  
  253.             else if ((_width > watermark.Width * 4) && (_height < watermark.Height * 4))  
  254.             {  
  255.                 bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);  
  256.   
  257.             }  
  258.             else if ((_width < watermark.Width * 4) && (_height > watermark.Height * 4))  
  259.             {  
  260.                 bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);  
  261.             }  
  262.             else  
  263.             {  
  264.                 if ((_width * watermark.Height) > (_height * watermark.Width))  
  265.                 {  
  266.                     bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);  
  267.   
  268.                 }  
  269.                 else  
  270.                 {  
  271.                     bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);  
  272.   
  273.                 }  
  274.   
  275.             }  
  276.   
  277.             WatermarkWidth = Convert.ToInt32(watermark.Width * bl);  
  278.             WatermarkHeight = Convert.ToInt32(watermark.Height * bl);  
  279.   
  280.             switch (_watermarkPosition)  
  281.             {  
  282.                 case "WM_TOP_LEFT":  
  283.                     xpos = 10;  
  284.                     ypos = 10;  
  285.                     break;  
  286.                 case "WM_TOP_RIGHT":  
  287.                     xpos = _width - WatermarkWidth - 10;  
  288.                     ypos = 10;  
  289.                     break;  
  290.                 case "WM_BOTTOM_RIGHT":  
  291.                     xpos = _width - WatermarkWidth - 10;  
  292.                     ypos = _height - WatermarkHeight - 10;  
  293.                     break;  
  294.                 case "WM_BOTTOM_LEFT":  
  295.                     xpos = 10;  
  296.                     ypos = _height - WatermarkHeight - 10;  
  297.                     break;  
  298.             }  
  299.   
  300.             picture.DrawImage(  
  301.              watermark,  
  302.              new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight),  
  303.              0,  
  304.              0,  
  305.              watermark.Width,  
  306.              watermark.Height,  
  307.              GraphicsUnit.Pixel,  
  308.              imageAttributes);  
  309.   
  310.             watermark.Dispose();  
  311.             imageAttributes.Dispose();  
  312.         }  
  313.   
  314.         /// <summary>  
  315.         ///   加水印图片  
  316.         /// </summary>  
  317.         /// <param name="picture">imge 对象</param>  
  318.         /// <param name="WaterMarkPicPath">水印图片的地址</param>  
  319.         /// <param name="_watermarkPosition">水印位置</param>  
  320.         /// <param name="_width">被加水印图片的宽</param>  
  321.         /// <param name="_height">被加水印图片的高</param>  
  322.         private void addWatermarkImage(Graphics picture, string WaterMarkPicPath,  
  323.          string _watermarkPosition, int _width, int _height)  
  324.         {  
  325.             Image watermark = new Bitmap(WaterMarkPicPath);  
  326.   
  327.             this.addWatermarkImage(picture, watermark, _watermarkPosition, _width,  
  328.              _height);  
  329.         }  
  330.         #endregion  
  331.   
  332.         #region 生成缩略图  
  333.         /// <summary>  
  334.         /// 保存图片  
  335.         /// </summary>  
  336.         /// <param name="image">Image 对象</param>  
  337.         /// <param name="savePath">保存路径</param>  
  338.         /// <param name="ici">指定格式的编解码参数</param>  
  339.         private void SaveImage(Image image, string savePath, ImageCodecInfo ici)  
  340.         {  
  341.             //设置 原图片 对象的 EncoderParameters 对象  
  342.             EncoderParameters parameters = new EncoderParameters(1);  
  343.             parameters.Param[0] = new EncoderParameter(  
  344.              System.Drawing.Imaging.Encoder.Quality, ((long)90));  
  345.             image.Save(savePath, ici, parameters);  
  346.             parameters.Dispose();  
  347.         }  
  348.   
  349.         /// <summary>  
  350.         /// 获取图像编码解码器的所有相关信息  
  351.         /// </summary>  
  352.         /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>  
  353.         /// <returns>返回图像编码解码器的所有相关信息</returns>  
  354.         private ImageCodecInfo GetCodecInfo(string mimeType)  
  355.         {  
  356.             ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();  
  357.             foreach (ImageCodecInfo ici in CodecInfo)  
  358.             {  
  359.                 if (ici.MimeType == mimeType)  
  360.                     return ici;  
  361.             }  
  362.             return null;  
  363.         }  
  364.   
  365.         /// <summary>  
  366.         /// 生成缩略图  
  367.         /// </summary>  
  368.         /// <param name="sourceImagePath">原图片路径(相对路径)</param>  
  369.         /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>  
  370.         /// <param name="thumbnailImageWidth">缩略图的宽度(高度与按源图片比例自动生成)</param>  
  371.         public void ToThumbnailImages(  
  372.          string SourceImagePath,  
  373.          string ThumbnailImagePath,  
  374.          int ThumbnailImageWidth)  
  375.         {  
  376.             Hashtable htmimes = new Hashtable();  
  377.             htmimes[".jpeg"] = "image/jpeg";  
  378.             htmimes[".jpg"] = "image/jpeg";  
  379.             htmimes[".png"] = "image/png";  
  380.             htmimes[".tif"] = "image/tiff";  
  381.             htmimes[".tiff"] = "image/tiff";  
  382.             htmimes[".bmp"] = "image/bmp";  
  383.             htmimes[".gif"] = "image/gif";  
  384.   
  385.             // 取得原图片的后缀  
  386.             string sExt = SourceImagePath.Substring(  
  387.              SourceImagePath.LastIndexOf(".")).ToLower();  
  388.   
  389.             //从 原图片创建 Image 对象  
  390.             Image image = Image.FromFile(SourceImagePath);  
  391.             int num = ((ThumbnailImageWidth / 4) * 3);  
  392.             int width = image.Width;  
  393.             int height = image.Height;  
  394.   
  395.             //计算图片的比例  
  396.             if ((((double)width) / ((double)height)) >= 1.3333333333333333f)  
  397.             {  
  398.                 num = ((height * ThumbnailImageWidth) / width);  
  399.             }  
  400.             else  
  401.             {  
  402.                 ThumbnailImageWidth = ((width * num) / height);  
  403.             }  
  404.             if ((ThumbnailImageWidth < 1) || (num < 1))  
  405.             {  
  406.                 return;  
  407.             }  
  408.   
  409.             //用指定的大小和格式初始化 Bitmap 类的新实例  
  410.             Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num,  
  411.              PixelFormat.Format32bppArgb);  
  412.   
  413.             //从指定的 Image 对象创建新 Graphics 对象  
  414.             Graphics graphics = Graphics.FromImage(bitmap);  
  415.   
  416.             //清除整个绘图面并以透明背景色填充  
  417.             graphics.Clear(Color.Transparent);  
  418.   
  419.             graphics.SmoothingMode = SmoothingMode.HighQuality;  
  420.             graphics.InterpolationMode = InterpolationMode.High;  
  421.   
  422.             //在指定位置并且按指定大小绘制 原图片 对象  
  423.             graphics.DrawImage(image, new Rectangle(00, ThumbnailImageWidth, num));  
  424.             image.Dispose();  
  425.   
  426.             try  
  427.             {  
  428.                 //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件  
  429.                 SaveImage(bitmap, ThumbnailImagePath,  
  430.                  GetCodecInfo((string)htmimes[sExt]));  
  431.             }  
  432.             catch (System.Exception e)  
  433.             {  
  434.                 throw e;  
  435.             }  
  436.         }  
  437.         #endregion  
  438.     }  
  439.   
  440. //测试代码  
  441. private void button1_Click(object sender, EventArgs e)  
  442.         {  
  443.             string path = @"C:\pics\input\Goolge.png";  
  444.             string savepath = @"C:\pics\input\Goolge2.png";  
  445.             string thumpath = @"C:\pics\input\Goolge3.png";  
  446.             ImageWaterMark imgwm = new ImageWaterMark();  
  447.             Position ps = new Position();  
  448.             imgwm.addWaterMark(path, savepath, WaterMarkType.TextMark, "SHW",ps.WM_TOP_RIGHT);  
  449.             //imgwm.addWaterMark(path, savepath, WaterMarkType.TextMark,"SHW");  
  450.             //imgwm.ToThumbnailImages(path, thumpath, 50);  
  451.         }  

没有评论:

发表评论