Search code examples
c#system.drawingdrawstring

Drawing string on image and save with same name C#


I'm working on a project where I have to draw text from front end using fabric.js. I have the code to send json for drawing string ie canvas.tojson().

On server side I have a problem in c#. I have to save the image with same filename. If I try to delete the original file before saving, it says file is already in use by other program, and if I overwrite, it's not doing it either. How can I save file with same name after drawing image?

Here is my code

string file = "D:\\Folder\\file.jpg";
            Bitmap bitMapImage = new Bitmap(file);
            Graphics graphicImage = Graphics.FromImage(bitMapImage);
            graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
            graphicImage.DrawString("That's my boy!",new Font("Arial", 12, FontStyle.Bold),SystemBrushes.WindowText, new Point(100, 250));
            graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360);

            System.IO.File.Delete(file);

            bitMapImage.Save(file, ImageFormat.Jpeg); 

Solution

  • Just clone the original bitmap and dispose the original to make it release the file...

    Bitmap cloneImage = null;
    using (Bitmap bitMapImage = new Bitmap(file))
    {
        cloneImage = new Bitmap(bitMapImage);
    }
    
    
    using (cloneImage)
    {
        Graphics graphicImage = Graphics.FromImage(cloneImage);
        graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
        graphicImage.DrawString("That's my boy!", new Font("Arial", 12, FontStyle.Bold), SystemBrushes.WindowText, new Point(100, 250));
        graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360);
    
        System.IO.File.Delete(file);
    
        cloneImage.Save(file, ImageFormat.Jpeg);
    }