2016-11-29 1 views
0

画像に2つの透かしテキストを追加しようとしています。画像のサイズに関係なく、画像の左下と右下にそれぞれ1つずつ追加します。以下の私の方法です:透かし文字のフォントサイズ(寸法は同じだが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ピクセルのサイズを持つ2つの画像があり、最初の画像はdpi72であり、2番目の画像がdpiの画像が240であるとします。上記の方法は、72dpiの画像ではうまく動作していますが、240dpiの画像では、透かしテキストのfont sizeが大きくなりすぎて画像にオーバーフローします。 dpiの画像で正しくfont sizeを計算する方法は同じですが、

+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); 
関連する問題