我想在图像中心对角放置水印。我的代码运行良好,但水印并未出现在每张图像的中心。我认为在硬编码值的位置放置水印文本存在问题。我该如何编写用于放置水印文本的通用公式。
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/