46

I have the following problem. I want to make some graphics in bitmap image like bond form

i can write a text in image
but i will write more text in various positions

Bitmap a = new Bitmap(@"path\picture.bmp");

using(Graphics g = Graphics.FromImage(a))
{
    g.DrawString(....); // requires font, brush etc
}

How can I write text and save it, and write another text in saved image.

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
Mr Alemi
  • 830
  • 1
  • 10
  • 21

5 Answers5

99

To draw multiple strings, call graphics.DrawString multiple times. You can specify the location of the drawn string. This example we will draw two strings "Hello", "Word" ("Hello" in blue color upfront "Word" in red color):

string firstText = "Hello";
string secondText = "World";

PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);

string imageFilePath = @"path\picture.bmp"
Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file

using(Graphics graphics = Graphics.FromImage(bitmap))
{
    using (Font arialFont =  new Font("Arial", 10))
    {
        graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation);
        graphics.DrawString(secondText, arialFont, Brushes.Red, secondLocation);
    }
}

bitmap.Save(imageFilePath);//save the image file

Edit: "I Add a load and save code".

You can open the bitmap file any time Image.FromFile, and draw a new text on it using the above code. and then save the image file bitmap.Save

LocustHorde
  • 6,361
  • 16
  • 65
  • 94
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
  • @wahab: check the answer edits. is that what you are asking for? – Jalal Said Jul 26 '11 at 08:33
  • @wahab: This is usually a problem in the file path. check your file path, a correct path looks like: `string path = @"C:\my image.bmp"; – Jalal Said Jul 27 '11 at 05:12
  • 1
    using(Graphics graphics = Graphics.FromImage(bitmap)) { using (Font arialFont = new Font("Arial", 10) { graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation); bitmap.Save(newpath);//save the image file graphics.DrawString(secondText, arialFont, Brushes.Red, secondLocation); bitmap.Save(newpath);//save the image file } } it worked – Mr Alemi Jul 27 '11 at 08:40
  • @wahab: Glad it worked for you :) don't forget to mark the answer as the [accepted answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) if it answers your question. – Jalal Said Jul 27 '11 at 08:43
  • And write text with background color in image ? – Kiquenet Dec 28 '13 at 10:18
  • @Kiquenet you can fill rectangle with your prefaired color, like using the graphics object in the example, so `graphics.FillRectangle(yourBackgroundSize ....); then graphics.DrawString(....)` – Jalal Said Dec 30 '13 at 10:11
  • I had to read the first phrase of your first sentence and I still don't understand it – LocustHorde Jan 24 '18 at 15:21
  • 1
    @LocustHorde To draw multiple `strings` in which each `string` need to be located at different place or `Point` within a given `Image`, you need to call the `graphics.DrawString` function multiple times and specify the location for each of those strings. – Jalal Said Feb 14 '18 at 11:25
  • 1
    Thanks! much better now – LocustHorde Feb 14 '18 at 17:21
  • @JamshaidKamran: yes, background-less png means image with Alpha channel, you can load/create image with alpha channel (32bit as 8 bits for alpha) and draw on top of it using the above.. – Jalal Said Jan 17 '19 at 09:30
  • The one thing missing from all these answers is "How do I know if the string will fit?" (or "How can I fit the bitmap to the string perfectly?"). The answer is to use [Graphics.MeasureString](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.measurestring?view=netframework-4.8) – BlueRaja - Danny Pflughoeft Oct 06 '19 at 10:01
7

Here's an example of a call to Graphics.DrawString, taken from here:

g.DrawString("My\nText", new Font("Tahoma", 40), Brushes.White, new PointF(0, 0));

It obviously relys on having a font called Tahoma installed.

The Brushes class has many built-in brushes.

See also, the MSDN page for Graphics.DrawString.

George Duckett
  • 31,770
  • 9
  • 95
  • 162
6

To save changes to the same file, I had to combine Jalal Said's answer and NSGaga's answer on this question. You need to create a new Bitmap object based on the old one, dispose old Bitmap object, then save using the new object:

string firstText = "Hello";
string secondText = "World";

PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);

string imageFilePath = @"path\picture.bmp";

Bitmap newBitmap;
using (var bitmap = (Bitmap)Image.FromFile(imageFilePath))//load the image file
{
    using(Graphics graphics = Graphics.FromImage(bitmap))
    {
        using (Font arialFont =  new Font("Arial", 10))
        {
            graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation);
            graphics.DrawString(secondText, arialFont, Brushes.Red, secondLocation);
        }
    }
    newBitmap = new Bitmap(bitmap);
}

newBitmap.Save(imageFilePath);//save the image file
newBitmap.Dispose();
Ibrahim
  • 183
  • 1
  • 6
1
    public string imageFilePath = null;
    public string textOnImage = null;

    public Image baseImage;
    public Image modifiedImage;

    public int xcoOrdinate = 0;
    public int ycoOrdinate = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void buttonLoadImage_Click(object sender, EventArgs e)
    {
        try
        {
            OpenFileDialog uploadfileDialog = new OpenFileDialog();
            uploadfileDialog.Filter = "All Files (*.*)|*.*";
            uploadfileDialog.Multiselect = false;

            if (uploadfileDialog.ShowDialog() == DialogResult.OK)
            {
                imageFilePath = uploadfileDialog.FileName;
            }

            baseImage = Image.FromFile(imageFilePath);
            modifiedImage = (Image)baseImage.Clone();
            pictureBoxToShowPic.Image = baseImage;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Source + " : " + ex.Message);
        }            
    }

    public void paint()
    {
        try
        {
            Graphics g = Graphics.FromImage(modifiedImage);
            using (Font myfont = new Font("Arial", 14))
            {
                var format = new StringFormat
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                };

                g.DrawString(textOnImage, myfont, Brushes.Black, new Point(xcoOrdinate, ycoOrdinate), format);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Source + " : " + ex.Message);
        }
    }

    private void buttonAddText_Click(object sender, EventArgs e)
    {
        try
        {
            textOnImage = textBoxWriteText.Text;
            paint();
            pictureBoxToShowPic.Image = modifiedImage;
            pictureBoxToShowPic.Refresh();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Source + " : " + ex.Message);
        }
    }

    private void pictureBoxToShowPic_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        try
        {
            xcoOrdinate = e.X;
            ycoOrdinate = e.Y;
        }            
        catch (Exception ex)
        {
            MessageBox.Show(ex.Source + " : " + ex.Message);
        }
    }

    private void buttonSaveImage_Click(object sender, EventArgs e)
    {
        try
        {
            SaveFileDialog savefileDialog = new SaveFileDialog();

            savefileDialog.Filter = "Images|*.jpg ; *.png ; *.bmp";

            if (savefileDialog.ShowDialog() == DialogResult.OK)
            {
                imageFilePath = savefileDialog.FileName;
            }

            modifiedImage.Save(imageFilePath);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Source + " : " + ex.Message);
        }
    }
  • I found a more suitable solution and this one works for me. By this one, we can add text dynamically in various positions. Double Click on the image, where you want to add text. Remember that keep your picture size property normal, otherwise, with the mouse position, the original position where you want to add text is not detected. And by this solution, you can save the modified image properly. – Ahsan Habib Shuvo Oct 06 '19 at 13:53
-8

If Someone has trouble with this code lines:

using(Graphics graphics = Graphics.FromImage(bitmap))

The solution is :

Bitmap bitmap = (Bitmap)**System.Drawing.Image.FromFile**(@"C:\Documents and Settings\", true);
Cleb
  • 25,102
  • 20
  • 116
  • 151
  • 1
    What problem is this supposed to solve? The original line of code is simple and clear and should work. The new line of code... I'm not even clear on what it does, and I certainly can't tell why. – Bruce Dawson Jan 18 '16 at 02:31