在C#中使用WaterMarking图像?

1 c# math geometry

我想在对角线的中心放置水印.我的代码做得很好但是水印没有出现在每个图像的中心.我认为水印文本的位置存在问题我硬编码值.如何编写通用公式为水印文本的位置.

    private MemoryStream ApplyWaterMark(MemoryStream stream)
        {

            System.Drawing.Image Im = System.Drawing.Image.FromStream(stream);                // 
            Graphics g = Graphics.FromImage(Im);

            // Create a solid brush to write the watermark text on the image
            Brush myBrush = new SolidBrush(System.Drawing.Color.FromArgb(25,
            System.Drawing.Color.LightSteelBlue));

            var f = new System.Drawing.Font(FontFamily.GenericSerif, 30);
            // Calculate the size of the text
            SizeF sz = g.MeasureString("TEST WATER MARK", f);

            int X, Y;
            X = ((int)(Im.Width - sz.Width) / 2)-1162;
            Y = ((int)(Im.Height + sz.Height) / 2)-127;



            g.RotateTransform(-45f);
            g.DrawString("TEST WATER MARK", f, myBrush,new System.Drawing.Point(X, Y));
            g.RotateTransform(45f);

            Im.Save(OutPutStream, ImageFormat.Png);//save image with dynamic watermark

            return OutPutStream;
        }
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以通过这种方式对角设置水印

     Bitmap newBitmap = new Bitmap(bitmap);
     Graphics g = Graphics.FromImage(newBitmap);

     // Trigonometry: Tangent = Opposite / Adjacent
     double tangent = (double)newBitmap.Height / 
                      (double)newBitmap.Width;

     // convert arctangent to degrees
     double angle = Math.Atan(tangent) * (180/Math.PI);

     // a^2 = b^2 + c^2 ; a = sqrt(b^2 + c^2)
     double halfHypotenuse =(Math.Sqrt((newBitmap.Height 
                            * newBitmap.Height) +
                            (newBitmap.Width * 
                            newBitmap.Width))) / 2;

     // Horizontally and vertically aligned the string
     // This makes the placement Point the physical 
     // center of the string instead of top-left.
     StringFormat stringFormat = new StringFormat();
     stringFormat.Alignment = StringAlignment.Center;
     stringFormat.LineAlignment=StringAlignment.Center;

     g.RotateTransform((float)angle);            
     g.DrawString(waterMarkText, font, new SolidBrush(color),
                  new Point((int)halfHypotenuse, 0), 
                  stringFormat);
Run Code Online (Sandbox Code Playgroud)