[英]watermark text font size on image with same dimensions but different dpi
我试图在图像上添加两个水印文本,一个在图像的左下角,另一个在图像的右下角,与图像尺寸无关。 以下是我的方法:
public void AddWaterMark(string leftSideText, string rightSideText, string imagePath)
{
string firstText = leftSideText;
string secondText = rightSideText;
Bitmap bitmap = (Bitmap)Image.FromFile(imagePath);//load the image file
PointF firstLocation = new PointF((float)(bitmap.Width * 0.035), bitmap.Height - (float)(bitmap.Height * 0.06));
PointF secondLocation = new PointF(((float)((bitmap.Width / 2) + ((bitmap.Width / 2) * 0.6))), bitmap.Height - (float)(bitmap.Height * 0.055));
int opacity = 155, baseFontSize = 50;
int leftTextSize = 0, rightTextSize = 0;
leftTextSize = (bitmap.Width * baseFontSize) / 1920;
rightTextSize = leftTextSize - 5;
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Font arialFontLeft = new Font(FontFamily.GenericSerif, leftTextSize);
Font arialFontRight = new Font(FontFamily.GenericSerif, rightTextSize);
graphics.DrawString(firstText, arialFontLeft, new SolidBrush(Color.FromArgb(opacity, Color.White)), firstLocation);
graphics.DrawString(secondText, arialFontRight, new SolidBrush(Color.FromArgb(opacity, Color.White)), secondLocation);
}
string fileLocation = HttpContext.Current.Server.MapPath("~/Images/Albums/") + Path.GetFileNameWithoutExtension(imagePath) + "_watermarked" + Path.GetExtension(imagePath);
bitmap.Save(fileLocation);//save the image file
bitmap.Dispose();
if (File.Exists(imagePath))
{
File.Delete(imagePath);
File.Move(fileLocation, fileLocation.Replace("_watermarked", string.Empty));
}
}
我面临的问题是正确设置水印文本的font size
。 假设有两张尺寸为1600 x 900
像素的图像,第一张图像的dpi
为72
,第二张图像的dpi
为240
。 上面的方法对于72
dpi的图像效果很好,但是对于240
dpi
的图像,水印文本的font size
变得太大并在图像上溢出。 如何使用不同dpi
但尺寸相同的图像正确计算font size
?
这个简单的技巧应该起作用:
在应用文本之前 ,请设置图像的dpi
。 应用文本后,将其重置为先前的值。
float dpiXNew = 123f;
float dpiYNew = 123f;
float dpiXOld = bmp.HorizontalResolution;
float dpiYOld = bmp.VerticalResolution;
bmp.SetResolution(dpiXNew, dpiYNew);
using (Graphics g = Graphics.FromImage(bmp))
{
TextRenderer.DrawText(g, "yourText", ....)
...
}
bmp.SetResolution(dpiXOld, dpiYOld);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.