示例#1
0
        /// <summary>
        /// 给图片添加文字水印
        /// </summary>
        /// <param name="srcFile">源图片存放路径</param>
        /// <param name="destFile">目标图片存放路径</param>
        /// <param name="fontSize">字号,可超过72号的</param>
        /// <param name="throwException">出现异常时是否抛出</param>
        /// <param name="text">要添加的文字</param>
        public static bool AddWatermarkText(string srcFile, string destFile, int fontSize, string text)
        {
            if (string.IsNullOrWhiteSpace(srcFile) || string.IsNullOrWhiteSpace(destFile))
            {
                throw new Exception("源图或目标图片的存放路径都不能为空");
            }


            System.Drawing.Image img     = null;
            Graphics             picture = null;
            Font         crFont          = null;
            StringFormat StrFormat       = new StringFormat();
            SolidBrush   semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));
            SolidBrush   semiTransBrush  = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

            try
            {
                img     = System.Drawing.Image.FromFile(srcFile);
                picture = Graphics.FromImage(img);

                SizeF crSize = new SizeF();
                crFont = new Font("arial", fontSize, FontStyle.Bold);
                crSize = picture.MeasureString(text, crFont);

                float xpos = 0;
                float ypos = 0;

                xpos = (img.Width - crSize.Width) / 2;
                ypos = (img.Height - crSize.Height) / 2;

                StrFormat.Alignment = StringAlignment.Near;
                picture.DrawString(text, crFont, semiTransBrush2, xpos + 1, ypos + 1, StrFormat);
                picture.DrawString(text, crFont, semiTransBrush, xpos, ypos, StrFormat);

                string destPath = Path.GetDirectoryName(destFile);
                if (!string.IsNullOrWhiteSpace(destPath))
                {
                    if (!Directory.Exists(destPath))
                    {
                        Directory.CreateDirectory(destPath);
                    }
                }
                img.Save(destFile);
                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception("给图片添加水印时发生异常:" + ex);
            }
            finally
            {
                crFont.DisposeIfNotNull();
                StrFormat.DisposeIfNotNull();
                semiTransBrush2.DisposeIfNotNull();
                semiTransBrush.DisposeIfNotNull();
                picture.DisposeIfNotNull();
                img.DisposeIfNotNull();
            }
        }