【问题标题】:watermark text font size on image with same dimensions but different dpi具有相同尺寸但不同dpi的图像上的水印文本字体大小
【发布时间】:2016-11-29 18:07:30
【问题描述】:

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

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 像素尺寸,第一个图像具有72dpi,第二个图像具有240dpi。上面的方法对于带有72 dpi 的图像效果很好,但是对于带有240 dpi 的图像,水印文本的font size 变得太大并溢出图像。如何用不同dpi但尺寸相同的图像正确计算font size

【问题讨论】:

  • 所以您实际上希望字体更小以适应更大的 DPI 值? (字体大小以像素为单位,与 DPI 无关)

标签: c# watermark


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多