2016-11-29 62 views
0

我想在圖像上添加兩個水印文字,一個在圖像底部左側,另一個在底部右側,與圖像尺寸無關。以下是我的方法:相同尺寸但不同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的圖像工作正常,但對於圖像240dpifont size的水印文本變得太大並溢出圖像。如何正確計算font size與不同dpi的圖像但具有相同的尺寸?

+0

因此,您是否希望字體對於較大的DPI值更小? (字體大小以像素爲單位而不是DPI相關) – grek40

回答

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); 
相關問題