具有相同尺寸但dpi不同的图像上的水印文字字体大小

时间:2016-11-29 04:28:27

标签: c# watermark

我正在尝试在图像上添加两个水印文本,一个位于图像的左下角,另一个位于图像的右下侧,与图像尺寸无关。以下是我的方法:

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像素尺寸,第一个图像的dpi72,第二个图像的dpi240。上述方法适用于72 dpi的图像,但对于240 dpi的图像,水印文字的font size变得太大而且溢出图像。如何使用不同font size但具有相同尺寸的图片正确计算dpi

1 个答案:

答案 0 :(得分:1)

这个简单的技巧应该有效:

应用文本之前设置图片的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);
相关问题