1. 程式人生 > >生成水印

生成水印

point rendering regular sha returns wid mod res poi

        /// <summary>
        /// 創建圖片字節數組
        /// </summary>
        /// <returns></returns>
        private byte[] CreateImgData(string text)
        {
            byte[] resData = null;
            using (var img = new Bitmap(300, 300))
            {
                using (var graphics = Graphics.FromImage(img))
                {
                    //消除鋸齒
                    graphics.SmoothingMode = SmoothingMode.AntiAlias;
                    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

                    //字體設置(根據實際情況提供自定義字體的路徑)
                    var tffFilePath = Path.Combine(“方正彩雲_GBK.ttf”); ;
                    PrivateFontCollection pfc = new PrivateFontCollection();
                    pfc.AddFontFile(tffFilePath);
                    var font = new Font(pfc.Families[0], 24, FontStyle.Regular);

                    //文字信息
                    var size = graphics.MeasureString(text, font);
                    var textPoint = new PointF((img.Width - size.Width) / 2, (img.Height - size.Height) / 2);

                    //旋轉
                    Matrix mtxSave = graphics.Transform;
                    Matrix mtxRotate = graphics.Transform;
                    mtxRotate.RotateAt(-45f, new PointF(img.Width / 2, img.Height / 2));
                    graphics.Transform = mtxRotate;

                    //繪制文字
                    Brush b = new SolidBrush(Color.FromArgb(128, 204, 204, 204));
                    graphics.DrawString(text, font, b, (img.Width - size.Width) / 2, (img.Height - size.Height) / 2);

                    //輸出字節數組
                    using (var memoryStream = new MemoryStream())
                    {
                        img.Save(memoryStream, ImageFormat.Png);
                        resData = memoryStream.ToArray();
                    }

                }
            }
            return resData;
        }

  

生成水印