簡體   English   中英

具有相同尺寸但不同dpi的圖像上的水印文本字體大小

[英]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像素的圖像,第一張圖像的dpi72 ,第二張圖像的dpi240 上面的方法對於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM