2012-02-27 88 views
0

我創建了一個處理程序上的圖像調用其下面寫書寫文字(不影響大小)

private bool HavException { get; set; } 
private string ExceptionMessage { get; set; } 
public Bitmap SourceImage { get; set; } 
public Bitmap DestinationImage { get; set; } 
public ImageMethods() 
{ 
    HavException = false; 
    ExceptionMessage = string.Empty; 
} 
public Image AddWatermarkText(Image img, string textOnImage) 
{ 
    try 
    { 
     textOnImage = ConfigurationManager.AppSettings["textOnImage"]; 
     var opacity = Int32.Parse(ConfigurationManager.AppSettings["opicity"]); 
     var red = Int32.Parse(ConfigurationManager.AppSettings["red"]); 
     var green = Int32.Parse(ConfigurationManager.AppSettings["green"]); 
     var blue = Int32.Parse(ConfigurationManager.AppSettings["blue"]); 
     var fontSize = Int32.Parse(ConfigurationManager.AppSettings["fontSize"]); 
     var fontName = ConfigurationManager.AppSettings["fontName"]; 

     var lobFromImage = Graphics.FromImage(img); 
     var lobFont = new Font(fontName, fontSize, FontStyle.Bold); 
     var lintTextHw = lobFromImage.MeasureString(textOnImage, lobFont); 
     var lintTextOnImageWidth = (int)lintTextHw.Width; 
     var lintTextOnImageHeight = (int)lintTextHw.Height; 
     var lobSolidBrush = new SolidBrush(Color.FromArgb(opacity, Color.FromArgb(red, green, blue))); 
     // lobFromImage.Clear(Color.White); 
     lobFromImage.DrawImage(img, img.Height, img.Width); 

     var posLeft = (img.Width - lintTextOnImageWidth)/2; 
     posLeft = posLeft > 0 ? posLeft : 5; 
     var lobPoint = new Point(posLeft, (img.Height/2) - (lintTextOnImageHeight/2)); 
     // var lobPoint = new Point(RandomNumber(0, img.Width - lintTextOnImageWidth), RandomNumber(0, img.Height - lintTextOnImageHeight)); 
     lobFromImage.DrawString(textOnImage, lobFont, lobSolidBrush, lobPoint); 

     lobFromImage.Save(); 
     lobFromImage.Dispose(); 
     lobSolidBrush.Dispose(); 
     lobFont.Dispose(); 
    } 
    catch (Exception ex) 
    { 
     HavException = true; 
     ExceptionMessage = ex.Message; 
    } 
    return img; 
} 

每件事功能工作正常,但圖像的尺寸越來越書寫文本增加了2至3倍。 有沒有什麼辦法可以增加太多的尺寸。我有JPG作爲原始圖像。

感謝

回答

1

下面的調用是沒有意義的,並可能是罪魁禍首的膨脹圖像尺寸:

lobFromImage.DrawImage(img, img.Height, img.Width); 

這將在(高度,寬度)位置上繪製原始圖像 - 例如,如果您的圖像尺寸爲200 x 100,則上述調用將在(100,200)位置繪製圖像,並可能將您的畫布拉伸至300 x 300的尺寸。

爲了添加水印,您所需要做的就是繪製文本 - 所以我的猜測是通過刪除上面的行可能會做到這一點。

另外lobFromImage.Save();看起來很可疑 - 它將圖形的對象狀態保存在堆棧中,並且與將圖像保存在磁盤上沒有任何關係。

+0

我已經刪除了這兩行,但圖像大小仍在增加。它獲得了原來尺寸的所有最大一倍。你現在是更好的方法嗎? – 2012-02-27 11:59:17

+0

@krshekhar,你如何打開/保存你的圖像文件?發佈該代碼以及! – VinayC 2012-02-27 12:02:43

+0

我有一個集中的圖像服務器供不同的應用程序使用。我爲圖像服務器的任何請求和響應創建了一個http處理程序。這是如下 – 2012-02-27 12:13:44