c# - C# 中图像上的水印?

标签 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;
        }

最佳答案

可以这样设置对角线水印

     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);

关于c# - C# 中图像上的水印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12725643/

相关文章:

c# - 即使文件存在于我的路径中,File.Exist 条件在 asp.net 中不起作用

algorithm - 获取球体上均匀分布的点的区域

c++ - 如何将数字0到n均匀分配到m个不同的容器中

graphics - 如何测试线段是否与二维轴对齐矩形相交?

python - 应该接触的匀称多边形却没有

c# - 如何在c#中定义一个等值数组?

c# - 将查询字符串转换为 .Net 中的键值对

c# - Linq toEntity contains 不适用于预存储的变量

python - C++ 中的长数字

c++ - 在 OpenGL 上画圆