如何对齐图像中的水印
How to align watermark in an image
我正在尝试为一张图片添加多个水印,中间有一些空隙。不过,我已经能够通过两个小警告实现这一目标。
我想要的是:
- 水印应垂直居中对齐。
- 当图片的宽度and/or高度不足时,程序需要停止添加水印(这样就不会切割文本)。
我的代码是:
static void WatermarkedImage(string path, string fileName, string message, string destFileName)
{
using (Image image = Image.FromFile(path + fileName))
{
Graphics graphics = Graphics.FromImage(image);
Font font = new Font("Arial", 20, FontStyle.Bold);
SolidBrush brush = new SolidBrush(Color.FromArgb(150, 255, 0, 0));
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
int index = 0;
float offsetX = image.Width / 3;
float offsetY = image.Height / 3;
int increment = Convert.ToInt32(image.Height * 0.15);
while (offsetY * 1.25 < image.Height)
{
Matrix matrix = new Matrix();
matrix.Translate(offsetX, offsetY);
matrix.Rotate(-45.0f);
graphics.Transform = matrix;
graphics.DrawString(message, font, brush, 0, 50, format);
offsetX += increment;
offsetY += increment;
index++;
}
image.Save(path + destFileName);
}
}
这就是我得到的结果:
期望的输出。
非常感谢任何帮助。
谢谢!
Update-1
您想要的输出在 x 轴上没有任何偏移量,因此您根本不应该增加 x 偏移量。
offsetY += increment;
index++;
}
while (offsetY * 1.25 < image.Height);
image.Save(path + destFileName);
要检查所有文本是否都在图片内,请使用 MeasureString 查看字符串的大小。由此您可以构建一个矩形,使用矩阵变换所述矩形的每个角,并检查它们是否都在图像内。
我正在尝试为一张图片添加多个水印,中间有一些空隙。不过,我已经能够通过两个小警告实现这一目标。
我想要的是:
- 水印应垂直居中对齐。
- 当图片的宽度and/or高度不足时,程序需要停止添加水印(这样就不会切割文本)。
我的代码是:
static void WatermarkedImage(string path, string fileName, string message, string destFileName)
{
using (Image image = Image.FromFile(path + fileName))
{
Graphics graphics = Graphics.FromImage(image);
Font font = new Font("Arial", 20, FontStyle.Bold);
SolidBrush brush = new SolidBrush(Color.FromArgb(150, 255, 0, 0));
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
int index = 0;
float offsetX = image.Width / 3;
float offsetY = image.Height / 3;
int increment = Convert.ToInt32(image.Height * 0.15);
while (offsetY * 1.25 < image.Height)
{
Matrix matrix = new Matrix();
matrix.Translate(offsetX, offsetY);
matrix.Rotate(-45.0f);
graphics.Transform = matrix;
graphics.DrawString(message, font, brush, 0, 50, format);
offsetX += increment;
offsetY += increment;
index++;
}
image.Save(path + destFileName);
}
}
这就是我得到的结果:
期望的输出。
非常感谢任何帮助。 谢谢!
Update-1
您想要的输出在 x 轴上没有任何偏移量,因此您根本不应该增加 x 偏移量。
offsetY += increment;
index++;
}
while (offsetY * 1.25 < image.Height);
image.Save(path + destFileName);
要检查所有文本是否都在图片内,请使用 MeasureString 查看字符串的大小。由此您可以构建一个矩形,使用矩阵变换所述矩形的每个角,并检查它们是否都在图像内。