使用Graphis.DrawString method在指定位置添加一個文本(用指定的顏色,字體,字體大小等):
try
{
var image = Image.FromFile("d:\\temp\\image.jpg");
using (var graphics = Graphics.FromImage(image))
{
var font = new Font(FontFamily.GenericSansSerif, 16.0f);
graphics.DrawString("copyright 2014", font, Brushes.Red, new Point(10, 10));
}
image.Save("d:\\temp\\image_copyright.jpg");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
原圖:

w ^第i個所添加的文本:

如果可能的話(和適當的)嘗試總是包裹在using
聲明Graphics
對象的創建。使用Graphics.FromImage method從現有圖像創建一個圖形對象(如你的情況)。這樣,不再需要的對象的處理將由框架自動完成。使用Point
對象將文字放在所需的位置,其中(0,0)
是圖像的左上角。
UPDATE
如果你想在一個自定義的位置添加文本在PictureBox
,然後綁定PictureBox.MouseClick
事件,以客戶座標轉換的座標,使用轉換鼠標座標來定位文本在圖像上並刷新PictureBox
控制中,圖像被修改後:
private void pictureBox_MouseClick(object sender, MouseEventArgs e)
{
var text = !String.IsNullOrEmpty(textBox.Text) ? textBox.Text : "copyright 2014";
var imageCoordinates = translateStretchImageMousePosition(new Point(e.X, e.Y));
using (var graphics = Graphics.FromImage(pictureBox.Image))
{
var font = new Font(FontFamily.GenericSansSerif, 16.0f);
graphics.DrawString(text, font, Brushes.Red, imageCoordinates);
}
pictureBox.Refresh();
}
的輸出是:

因爲PictureBox
具有圖像大小的不同模式,你需要計算點擊座標不同。如何做到這一點顯示在這CodeProject article。你也可以嘗試使用.NET框架提供的不同的client coordinate translation functions。
問題是,用戶必須能夠在應用程序運行時添加字符串。他應該能夠通過單擊圖像而不是在指定點(在代碼中)添加字符串。無論如何感謝回答。 –