ASP.NET(C#)图片加文字、图片水印

ASP.NET(C#)图片加文字、图片水印

一、图片上加文字:

  1. //using System.Drawing;  
  2. //using System.IO;  
  3. //using System.Drawing.Imaging;  
  4.   
  5. private void AddTextToImg(string fileName,string text)  
  6. {  
  7.    if(!File.Exists(MapPath(fileName)))  
  8.    {  
  9.        throw new FileNotFoundException("The file don't exist!");  
  10.    }  
  11.      
  12.    if( text == string.Empty )  
  13.    {  
  14.        return;  
  15.    }  
  16.    //还需要判断文件类型是否为图像类型,这里就不赘述了  
  17.   
  18.    System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(fileName));  
  19.    Bitmap bitmap = new Bitmap(image,image.Width,image.Height);  
  20.    Graphics g = Graphics.FromImage(bitmap);  
  21.   
  22.    float fontSize = 12.0f;    //字体大小  
  23.    float textWidth = text.Length*fontSize;  //文本的长度  
  24.    //下面定义一个矩形区域,以后在这个矩形里画上白底黑字  
  25.    float rectX = 0;          
  26.    float rectY = 0;  
  27.    float rectWidth = text.Length*(fontSize+8);  
  28.    float rectHeight = fontSize+8;  
  29.    //声明矩形域  
  30.    RectangleF textArea = new RectangleF(rectX,rectY,rectWidth,rectHeight);  
  31.   
  32.    Font font = new Font("宋体",fontSize);   //定义字体  
  33.    Brush whiteBrush = new SolidBrush(Color.White);   //白笔刷,画文字用  
  34.    Brush blackBrush = new SolidBrush(Color.Black);   //黑笔刷,画背景用  
  35.   
  36.    g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight);     
  37.   
  38.    g.DrawString(text,font,whiteBrush,textArea);  
  39.    MemoryStream ms = new MemoryStream( );  
  40.    //保存为Jpg类型  
  41.    bitmap.Save(ms,ImageFormat.Jpeg);  
  42.   
  43.    //输出处理后的图像,这里为了演示方便,我将图片显示在页面中了  
  44.    Response.Clear();  
  45.    Response.ContentType = "image/jpeg";  
  46.    Response.BinaryWrite( ms.ToArray() );  
  47.   
  48.    g.Dispose();  
  49.    bitmap.Dispose();  
  50.    image.Dispose();  
  51. }  

二、图片上加水印:

 

  1. //using System;   
  2. //using System.Web;   
  3. //using System.Drawing;   
  4. //using System.Drawing.Drawing2D;   
  5. //using System.Drawing.Imaging;   
  6. //using System.IO;   
  7. //using System.Reflection;   
  8.   
  9. /// <summary>   
  10. /// 给图片上水印   
  11. /// </summary>   
  12. /// <param name="filePath">原图片地址</param>   
  13. /// <param name="waterFile">水印图片地址</param>   
  14. public void MarkWater(string filePath,string waterFile)   
  15. {   
  16.     //GIF不水印   
  17.     int i = filePath.LastIndexOf(".");   
  18.     string ex = filePath.Substring(i,filePath.Length - i);   
  19.     if(string.Compare(ex,".gif",true) == 0)   
  20.     {   
  21.         return;   
  22.     }   
  23.   
  24.     string ModifyImagePath = BasePath + filePath;//修改的图像路径   
  25.     int lucencyPercent=25;   
  26.     Image modifyImage=null;   
  27.     Image drawedImage=null;   
  28.     Graphics g=null;   
  29.     try   
  30.     {   
  31.         //建立图形对象   
  32.         modifyImage=Image.FromFile(ModifyImagePath,true);   
  33.         drawedImage=Image.FromFile(BasePath + waterFile,true);   
  34.         g=Graphics.FromImage(modifyImage);   
  35.         //获取要绘制图形坐标   
  36.         int x=modifyImage.Width-drawedImage.Width;   
  37.         int y=modifyImage.Height-drawedImage.Height;   
  38.         //设置颜色矩阵   
  39.         float[][] matrixItems ={   
  40.             new float[] {1, 0, 0, 0, 0},   
  41.             new float[] {0, 1, 0, 0, 0},   
  42.             new float[] {0, 0, 1, 0, 0},   
  43.             new float[] {0, 0, 0, (float)lucencyPercent/100f, 0},   
  44.             new float[] {0, 0, 0, 0, 1}};   
  45.   
  46.         ColorMatrix colorMatrix = new ColorMatrix(matrixItems);   
  47.         ImageAttributes imgAttr=new ImageAttributes();   
  48.         imgAttr.SetColorMatrix(colorMatrix,ColorMatrixFlag.Default,ColorAdjustType.Bitmap);   
  49.         //绘制阴影图像   
  50.         g.DrawImage(drawedImage,new Rectangle(x,y,drawedImage.Width,drawedImage.Height),10,10,drawedImage.Width,drawedImage.Height,GraphicsUnit.Pixel,imgAttr);   
  51.         //保存文件   
  52.         string[] allowImageType={".jpg",".gif",".png",".bmp",".tiff",".wmf",".ico"};   
  53.         FileInfo fi=new FileInfo(ModifyImagePath);   
  54.         ImageFormat imageType=ImageFormat.Gif;   
  55.         switch(fi.Extension.ToLower())   
  56.         {   
  57.             case ".jpg": imageType=ImageFormat.Jpeg; break;   
  58.             case ".gif": imageType=ImageFormat.Gif; break;   
  59.             case ".png": imageType=ImageFormat.Png; break;   
  60.             case ".bmp": imageType=ImageFormat.Bmp; break;   
  61.             case ".tif": imageType=ImageFormat.Tiff; break;   
  62.             case ".wmf": imageType=ImageFormat.Wmf; break;   
  63.             case ".ico": imageType=ImageFormat.Icon; break;   
  64.             defaultbreak;   
  65.         }   
  66.         MemoryStream ms=new MemoryStream();   
  67.         modifyImage.Save(ms,imageType);   
  68.         byte[] imgData=ms.ToArray();   
  69.         modifyImage.Dispose();   
  70.         drawedImage.Dispose();   
  71.         g.Dispose();   
  72.         FileStream fs=null;   
  73.         File.Delete(ModifyImagePath);   
  74.         fs=new FileStream(ModifyImagePath,FileMode.Create,FileAccess.Write);   
  75.         if(fs!=null)   
  76.         {   
  77.             fs.Write(imgData,0,imgData.Length);   
  78.             fs.Close();   
  79.         }   
  80.     }   
  81.     finally   
  82.     {   
  83.         try   
  84.         {   
  85.             drawedImage.Dispose();   
  86.             modifyImage.Dispose();   
  87.             g.Dispose();   
  88.         }   
  89.         catch  
  90.         {  
  91.         }   
  92.    }   
  93. }   

四、C#图片水印生成类(图片、文字、透明水印)

  1. /* 
  2.  * Class:WaterImage 
  3.  * Use for add a water Image to the picture both words and image 
  4.  * 2007.07.23   create the file 
  5.  * 
  6.  * http://www.freeatom.com/  欢迎您的来访 
  7.  *  
  8.  * 使用说明: 
  9.  *  建议先定义一个WaterImage实例 
  10.  *  然后利用实例的属性,去匹配需要进行操作的参数 
  11.  *  然后定义一个WaterImageManage实例 
  12.  *  利用WaterImageManage实例进行DrawImage(),印图片水印 
  13.  *  DrawWords()印文字水印 
  14.  *  
  15. -*/  
  16.   
  17. using System;  
  18. using System.Drawing;  
  19. using System.Drawing.Imaging;  
  20. using System.Drawing.Drawing2D;  
  21. using System.IO;  
  22. /// <summary>  
  23. /// 图片位置  
  24. /// </summary>  
  25. public enum ImagePosition  
  26. {  
  27.     LeftTop,        //左上  
  28.     LeftBottom,    //左下  
  29.     RightTop,       //右上  
  30.     RigthBottom,  //右下  
  31.     TopMiddle,     //顶部居中  
  32.     BottomMiddle, //底部居中  
  33.     Center           //中心  
  34. }  
  35.   
  36. /// <summary>  
  37. /// 水印图片的操作管理 Design by Gary Gong From Demetersoft.com  
  38. /// </summary>  
  39. public class WaterImageManage  
  40. {  
  41.     /// <summary>  
  42.     /// 生成一个新的水印图片制作实例  
  43.     /// </summary>  
  44.     public WaterImageManage ()  
  45.     {  
  46.         //  
  47.         // TODO: Add constructor logic here  
  48.         //  
  49.     }  
  50.   
  51.     /// <summary>  
  52.     /// 添加图片水印  
  53.     /// </summary>  
  54.     /// <param name="sourcePicture">源图片文件名</param>  
  55.     /// <param name="waterImage">水印图片文件名</param>  
  56.     /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param>  
  57.     /// <param name="position">位置</param>  
  58.     /// <param name="PicturePath" >图片的路径</param>  
  59.     /// <returns>返回生成于指定文件夹下的水印文件名</returns>  
  60.     public string  DrawImage(string sourcePicture,  
  61.                                       string waterImage,  
  62.                                       float alpha,  
  63.                                       ImagePosition position,  
  64.                                       string PicturePath )  
  65.     {  
  66.         //  
  67.         // 判断参数是否有效  
  68.         //  
  69.         if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty)  
  70.         {  
  71.             return sourcePicture;  
  72.         }  
  73.   
  74.         //  
  75.         // 源图片,水印图片全路径  
  76.         //  
  77.         string sourcePictureName = PicturePath + sourcePicture;  
  78.         string waterPictureName = PicturePath + waterImage;  
  79.         string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();  
  80.         string fileWaterExtension = System.IO.Path.GetExtension(waterPictureName).ToLower();  
  81.         //  
  82.         // 判断文件是否存在,以及类型是否正确  
  83.         //  
  84.         if (System.IO.File.Exists(sourcePictureName) == false ||   
  85.             System.IO.File.Exists(waterPictureName) == false ||(  
  86.             fileSourceExtension != ".gif" &&  
  87.             fileSourceExtension != ".jpg" &&  
  88.             fileSourceExtension != ".png") || (  
  89.             fileWaterExtension != ".gif" &&  
  90.             fileWaterExtension != ".jpg" &&  
  91.             fileWaterExtension != ".png")  
  92.             )  
  93.         {  
  94.             return sourcePicture;  
  95.         }  
  96.   
  97.         //  
  98.         // 目标图片名称及全路径  
  99.         //  
  100.         string targetImage = sourcePictureName.Replace ( System.IO.Path.GetExtension(sourcePictureName),"") + "_1101.jpg";  
  101.   
  102.         //  
  103.         // 将需要加上水印的图片装载到Image对象中  
  104.         //  
  105.         Image imgPhoto = Image.FromFile(sourcePictureName);  
  106.         //  
  107.         // 确定其长宽  
  108.         //  
  109.         int phWidth = imgPhoto.Width;  
  110.         int phHeight = imgPhoto.Height;  
  111.   
  112.         //  
  113.         // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。  
  114.         //  
  115.         Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);  
  116.   
  117.         //  
  118.         // 设定分辨率  
  119.         //   
  120.         bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);  
  121.   
  122.         //  
  123.         // 定义一个绘图画面用来装载位图  
  124.         //  
  125.         Graphics grPhoto = Graphics.FromImage(bmPhoto);  
  126.   
  127.         //  
  128.         //同样,由于水印是图片,我们也需要定义一个Image来装载它  
  129.         //  
  130.         Image imgWatermark = new Bitmap(waterPictureName);  
  131.           
  132.         //  
  133.         // 获取水印图片的高度和宽度  
  134.         //  
  135.         int wmWidth = imgWatermark.Width;  
  136.         int wmHeight = imgWatermark.Height;  
  137.   
  138.         //SmoothingMode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。  
  139.         // 成员名称   说明   
  140.         // AntiAlias      指定消除锯齿的呈现。    
  141.         // Default        指定不消除锯齿。    
  142.         // HighQuality  指定高质量、低速度呈现。    
  143.         // HighSpeed   指定高速度、低质量呈现。    
  144.         // Invalid        指定一个无效模式。    
  145.         // None          指定不消除锯齿。   
  146.         grPhoto.SmoothingMode = SmoothingMode.AntiAlias;  
  147.   
  148.         //  
  149.         // 第一次描绘,将我们的底图描绘在绘图画面上  
  150.         //  
  151.         grPhoto.DrawImage(imgPhoto,                                            
  152.                                     new Rectangle(0, 0, phWidth, phHeight),   
  153.                                     0,       
  154.                                     0,         
  155.                                     phWidth,     
  156.                                     phHeight,        
  157.                                     GraphicsUnit.Pixel);      
  158.   
  159.         //  
  160.         // 与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率  
  161.         //  
  162.         Bitmap bmWatermark = new Bitmap(bmPhoto);  
  163.         bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);  
  164.           
  165.         //  
  166.         // 继续,将水印图片装载到一个绘图画面grWatermark  
  167.         //  
  168.         Graphics grWatermark = Graphics.FromImage(bmWatermark);  
  169.   
  170.         //  
  171.         //ImageAttributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。  
  172.         //         
  173.         ImageAttributes imageAttributes = new ImageAttributes();  
  174.   
  175.         //  
  176.         //Colormap: 定义转换颜色的映射  
  177.         //  
  178.         ColorMap colorMap = new ColorMap();  
  179.   
  180.         //  
  181.         //我的水印图被定义成拥有绿色背景色的图片被替换成透明  
  182.         //  
  183.         colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);  
  184.         colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);  
  185.   
  186.         ColorMap[] remapTable = { colorMap };  
  187.   
  188.         imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);  
  189.   
  190.         float[][] colorMatrixElements = {   
  191.            new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f}, // red红色  
  192.            new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f}, //green绿色  
  193.            new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f}, //blue蓝色         
  194.            new float[] {0.0f,  0.0f,  0.0f,  alpha, 0.0f}, //透明度       
  195.            new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}};//  
  196.   
  197.         //  ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。  
  198.         //  ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。  
  199.         ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);  
  200.   
  201.   
  202.         imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,  
  203.          ColorAdjustType.Bitmap);  
  204.   
  205.         //  
  206.         //上面设置完颜色,下面开始设置位置  
  207.         //  
  208.         int xPosOfWm;  
  209.         int yPosOfWm;   
  210.   
  211.         switch (position)  
  212.         {  
  213.             case ImagePosition .BottomMiddle :  
  214.                 xPosOfWm = (phWidth-wmWidth ) / 2 ;  
  215.                 yPosOfWm = phHeight- wmHeight -10;  
  216.                 break ;  
  217.             case ImagePosition .Center :  
  218.                 xPosOfWm = (phWidth - wmWidth) / 2;  
  219.                 yPosOfWm = (phHeight-wmHeight ) / 2;  
  220.                 break ;  
  221.             case ImagePosition .LeftBottom :  
  222.                 xPosOfWm = 10;  
  223.                 yPosOfWm = phHeight - wmHeight - 10;  
  224.                 break ;  
  225.             case ImagePosition .LeftTop :  
  226.                 xPosOfWm = 10;  
  227.                 yPosOfWm = 10;  
  228.                 break;  
  229.             case ImagePosition .RightTop :  
  230.                 xPosOfWm = phWidth - wmWidth - 10;  
  231.                 yPosOfWm = 10;  
  232.                 break ;  
  233.             case ImagePosition .RigthBottom :  
  234.                 xPosOfWm = phWidth - wmWidth - 10;  
  235.                 yPosOfWm = phHeight - wmHeight - 10;  
  236.                 break ;  
  237.             case ImagePosition.TopMiddle :  
  238.                 xPosOfWm = (phWidth - wmWidth) / 2;  
  239.                 yPosOfWm = 10;  
  240.                 break ;  
  241.             default:  
  242.                 xPosOfWm = 10;  
  243.                 yPosOfWm = phHeight - wmHeight - 10;  
  244.                 break;  
  245.         }  
  246.   
  247.         //  
  248.         // 第二次绘图,把水印印上去  
  249.         //  
  250.         grWatermark.DrawImage(imgWatermark,  
  251.          new Rectangle(xPosOfWm,  
  252.                              yPosOfWm,  
  253.                              wmWidth,  
  254.                              wmHeight),   
  255.                              0,                
  256.                              0,            
  257.                              wmWidth,    
  258.                              wmHeight,     
  259.                              GraphicsUnit.Pixel,    
  260.                              imageAttributes);   
  261.   
  262.          
  263.         imgPhoto = bmWatermark;  
  264.         grPhoto.Dispose();  
  265.         grWatermark.Dispose();  
  266.   
  267.         //  
  268.         // 保存文件到服务器的文件夹里面  
  269.         //  
  270.         imgPhoto.Save(targetImage, ImageFormat.Jpeg);  
  271.         imgPhoto.Dispose();  
  272.         imgWatermark.Dispose();  
  273.         return targetImage.Replace (PicturePath,"");  
  274.     }  
  275.   
  276.     /// <summary>  
  277.     /// 在图片上添加水印文字  
  278.     /// </summary>  
  279.     /// <param name="sourcePicture">源图片文件</param>  
  280.     /// <param name="waterWords">需要添加到图片上的文字</param>  
  281.     /// <param name="alpha">透明度</param>  
  282.     /// <param name="position">位置</param>  
  283.     /// <param name="PicturePath">文件路径</param>  
  284.     /// <returns></returns>  
  285.     public string DrawWords(string sourcePicture,  
  286.                                       string waterWords,  
  287.                                       float alpha,  
  288.                                       ImagePosition position,  
  289.                                       string PicturePath)  
  290.     {  
  291.         //  
  292.         // 判断参数是否有效  
  293.         //  
  294.         if (sourcePicture == string.Empty || waterWords == string.Empty || alpha == 0.0 || PicturePath == string.Empty)  
  295.         {  
  296.             return sourcePicture;  
  297.         }  
  298.   
  299.         //  
  300.         // 源图片全路径  
  301.         //  
  302.         string sourcePictureName = PicturePath + sourcePicture;  
  303.         string fileExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();  
  304.   
  305.         //  
  306.         // 判断文件是否存在,以及文件名是否正确  
  307.         //  
  308.         if (System.IO.File.Exists(sourcePictureName) == false || (  
  309.             fileExtension != ".gif"  &&  
  310.             fileExtension != ".jpg" &&  
  311.             fileExtension != ".png" ))  
  312.         {  
  313.             return sourcePicture;  
  314.         }  
  315.   
  316.         //  
  317.         // 目标图片名称及全路径  
  318.         //  
  319.         string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_0703.jpg";  
  320.   
  321.         //创建一个图片对象用来装载要被添加水印的图片  
  322.         Image imgPhoto = Image.FromFile(sourcePictureName);  
  323.   
  324.         //获取图片的宽和高  
  325.         int phWidth = imgPhoto.Width;  
  326.         int phHeight = imgPhoto.Height;  
  327.   
  328.         //  
  329.         //建立一个bitmap,和我们需要加水印的图片一样大小  
  330.         Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);  
  331.   
  332.         //SetResolution:设置此 Bitmap 的分辨率  
  333.         //这里直接将我们需要添加水印的图片的分辨率赋给了bitmap  
  334.         bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);  
  335.   
  336.         //Graphics:封装一个 GDI+ 绘图图面。  
  337.         Graphics grPhoto = Graphics.FromImage(bmPhoto);  
  338.   
  339.         //设置图形的品质  
  340.         grPhoto.SmoothingMode = SmoothingMode.AntiAlias;  
  341.   
  342.         //将我们要添加水印的图片按照原始大小描绘(复制)到图形中  
  343.         grPhoto.DrawImage(  
  344.          imgPhoto,                                           //   要添加水印的图片  
  345.          new Rectangle(0, 0, phWidth, phHeight), //  根据要添加的水印图片的宽和高  
  346.          0,                                                     //  X方向从0点开始描绘  
  347.          0,                                                     // Y方向   
  348.          phWidth,                                            //  X方向描绘长度  
  349.          phHeight,                                           //  Y方向描绘长度  
  350.          GraphicsUnit.Pixel);                              // 描绘的单位,这里用的是像素  
  351.   
  352.         //根据图片的大小我们来确定添加上去的文字的大小  
  353.         //在这里我们定义一个数组来确定  
  354.         int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };  
  355.   
  356.         //字体  
  357.         Font crFont = null;  
  358.         //矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空  
  359.         SizeF crSize = new SizeF();  
  360.   
  361.         //利用一个循环语句来选择我们要添加文字的型号  
  362.         //直到它的长度比图片的宽度小  
  363.         for (int i = 0; i < 7; i++)  
  364.         {  
  365.             crFont = new Font("arial", sizes[i], FontStyle.Bold);  
  366.   
  367.             //测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。  
  368.             crSize = grPhoto.MeasureString(waterWords, crFont);  
  369.   
  370.             // ushort 关键字表示一种整数数据类型  
  371.             if ((ushort)crSize.Width < (ushort)phWidth)  
  372.                 break;  
  373.         }  
  374.   
  375.         //截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)  
  376.         int yPixlesFromBottom = (int)(phHeight * .05);  
  377.   
  378.         //定义在图片上文字的位置  
  379.         float wmHeight =  crSize.Height;  
  380.         float wmWidth = crSize .Width ;  
  381.   
  382.         float  xPosOfWm;  
  383.         float  yPosOfWm;   
  384.   
  385.         switch (position)  
  386.         {  
  387.             case ImagePosition .BottomMiddle :  
  388.                 xPosOfWm = phWidth / 2 ;  
  389.                 yPosOfWm = phHeight- wmHeight -10;  
  390.                 break ;  
  391.             case ImagePosition .Center :  
  392.                 xPosOfWm = phWidth / 2;  
  393.                 yPosOfWm = phHeight / 2;  
  394.                 break ;  
  395.             case ImagePosition .LeftBottom :  
  396.                 xPosOfWm = wmWidth;  
  397.                 yPosOfWm = phHeight - wmHeight - 10;  
  398.                 break ;  
  399.             case ImagePosition .LeftTop :  
  400.                 xPosOfWm = wmWidth/2 ;  
  401.                 yPosOfWm = wmHeight / 2;  
  402.                 break;  
  403.             case ImagePosition .RightTop :  
  404.                 xPosOfWm = phWidth - wmWidth - 10;  
  405.                 yPosOfWm = wmHeight;  
  406.                 break ;  
  407.             case ImagePosition .RigthBottom :  
  408.                 xPosOfWm = phWidth - wmWidth - 10;  
  409.                 yPosOfWm = phHeight - wmHeight - 10;  
  410.                 break ;  
  411.             case ImagePosition.TopMiddle :  
  412.                 xPosOfWm = phWidth / 2;  
  413.                 yPosOfWm = wmWidth;  
  414.                 break ;  
  415.             default:  
  416.                 xPosOfWm = wmWidth;  
  417.                 yPosOfWm = phHeight - wmHeight - 10;  
  418.                 break;  
  419.         }  
  420.   
  421.         //封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。  
  422.         StringFormat StrFormat = new StringFormat();  
  423.   
  424.         //定义需要印的文字居中对齐  
  425.         StrFormat.Alignment = StringAlignment.Center;  
  426.   
  427.         //SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。  
  428.         //这个画笔为描绘阴影的画笔,呈灰色  
  429.         int m_alpha = Convert .ToInt32 ( 256 * alpha);  
  430.         SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));  
  431.   
  432.         //描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果  
  433.         //DrawString 在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。  
  434.         grPhoto.DrawString(waterWords,                                    //string of text  
  435.                                    crFont,                                         //font  
  436.                                    semiTransBrush2,                            //Brush  
  437.                                    new PointF(xPosOfWm + 1, yPosOfWm + 1),  //Position  
  438.                                    StrFormat);  
  439.   
  440.         //从四个 ARGB 分量(alpha、红色、绿色和蓝色)值创建 Color 结构,这里设置透明度为153  
  441.         //这个画笔为描绘正式文字的笔刷,呈白色  
  442.         SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));  
  443.   
  444.         //第二次绘制这个图形,建立在第一次描绘的基础上  
  445.         grPhoto.DrawString(waterWords,                 //string of text  
  446.                                    crFont,                                   //font  
  447.                                    semiTransBrush,                           //Brush  
  448.                                    new PointF(xPosOfWm, yPosOfWm),  //Position  
  449.                                    StrFormat);  
  450.   
  451.         //imgPhoto是我们建立的用来装载最终图形的Image对象  
  452.         //bmPhoto是我们用来制作图形的容器,为Bitmap对象  
  453.         imgPhoto = bmPhoto;  
  454.         //释放资源,将定义的Graphics实例grPhoto释放,grPhoto功德圆满  
  455.         grPhoto.Dispose();  
  456.   
  457.         //将grPhoto保存  
  458.         imgPhoto.Save(targetImage, ImageFormat.Jpeg);  
  459.         imgPhoto.Dispose();  
  460.   
  461.         return targetImage.Replace(PicturePath, "");  
  462.     }  
  463. }  
  464.   
  465. /// <summary>  
  466. /// 装载水印图片的相关信息  
  467. /// </summary>  
  468. public class WaterImage  
  469. {  
  470.     public WaterImage ()  
  471.     {  
  472.   
  473.     }  
  474.   
  475.     private string m_sourcePicture;  
  476.     /// <summary>  
  477.     /// 源图片地址名字(带后缀)  
  478.     /// </summary>  
  479.     public string SourcePicture  
  480.     {  
  481.         get { return m_sourcePicture; }  
  482.         set { m_sourcePicture = value; }  
  483.     }  
  484.   
  485.     private string  m_waterImager;  
  486.     /// <summary>  
  487.     /// 水印图片名字(带后缀)  
  488.     /// </summary>  
  489.     public string  WaterPicture  
  490.     {  
  491.         get { return m_waterImager; }  
  492.         set { m_waterImager = value; }  
  493.     }  
  494.   
  495.     private float  m_alpha;  
  496.     /// <summary>  
  497.     /// 水印图片文字的透明度  
  498.     /// </summary>  
  499.     public float  Alpha  
  500.     {  
  501.         get { return m_alpha; }  
  502.         set { m_alpha = value; }  
  503.     }  
  504.   
  505.     private ImagePosition  m_postition;  
  506.     /// <summary>  
  507.     /// 水印图片或文字在图片中的位置  
  508.     /// </summary>  
  509.     public ImagePosition  Position  
  510.     {  
  511.         get { return m_postition; }  
  512.         set { m_postition = value; }  
  513.     }  
  514.   
  515.     private string  m_words;  
  516.     /// <summary>  
  517.     /// 水印文字的内容  
  518.     /// </summary>  
  519.     public string  Words  
  520.     {  
  521.         get { return m_words; }  
  522.         set { m_words = value; }  
  523.     }  
  524.        
  525. }  

三、 图片+水印(透明)函数

  1. <summary>  
  2.    /// 添加图片水印  
  3.    /// </summary>  
  4.    /// <param name="path">原图片绝对地址</param>  
  5.    /// <param name="Ext">文件后缀</param>  
  6.    public static string addWaterMark(string path,string fileExt)  
  7.    {  
  8.     System.Drawing.Image image = System.Drawing.Image.FromFile(path);  
  9.     Bitmap b = new Bitmap(image.Width, image.Height,System.Drawing.Imaging.PixelFormat.Format24bppRgb);  
  10.     Graphics g = Graphics.FromImage(b);  
  11.     g.Clear(Color.White);  
  12.     g.DrawImage(image, 0, 0, image.Width, image.Height);  
  13.   
  14.     Image watermark = new Bitmap(ConfigurationSettings.AppSettings["PersonalPath"] + @"images/logo.jpg");  
  15.   
  16.     System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();  
  17.     System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap();  
  18.     colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);  
  19.     colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);  
  20.     System.Drawing.Imaging.ColorMap[] remapTable = {colorMap};  
  21.     imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);  
  22.     float[][] colorMatrixElements = {  
  23.              new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},  
  24.              new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},  
  25.              new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},  
  26.              new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},  
  27.              new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}  
  28.             };  
  29.     System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);  
  30.     imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);  
  31.     int xpos = 0;  
  32.     int ypos = 0;  
  33.      
  34.     xpos = ((image.Width - watermark.Width) - 10);  
  35.     ypos = image.Height - watermark.Height - 10;  
  36.   
  37.     g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);  
  38.   
  39.     watermark.Dispose();  
  40.     imageAttributes.Dispose();  
  41.   
  42.   
  43.     //保存加水印过后的图片,删除原始图片  
  44.     Random ro=new Random((int)DateTime.Now.Ticks);  
  45.     string temppath = System.DateTime.Now.ToString("yyyy") + "//" + System.DateTime.Now.ToString("MMdd");  
  46.     string fileName = temppath + "//" + DateTime.Now.ToString("yyyyMMddHHmmss") + ro.Next(10000) + fileExt;  
  47.     string filepath = Functions.GetUserFactPath(User.GetUserFromSession().Adddate,User.GetUserFromSession().UserId) + "3//";  
  48.      
  49.   
  50.     b.Save(filepath + fileName);  
  51.     b.Dispose();  
  52.     image.Dispose();  
  53.     if(File.Exists(path))  
  54.     {  
  55.      File.Delete(path);  
  56.     }  
  57.   
  58.     return fileName;  
  59.    } 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值