c# 添加图片水印,可以指定水印位置+生成缩略图

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值