-1

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); 
halfer
  • 19,824
  • 17
  • 99
  • 186
skhurams
  • 2,133
  • 7
  • 45
  • 82
  • Also [see here](http://stackoverflow.com/questions/37736815/overwrite-image-picturebox-in-c-sharp/37741101?s=2|0.0000#37741101) – TaW Nov 25 '16 at 18:41

2 Answers2

2

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);
}
L.B
  • 114,136
  • 19
  • 178
  • 224
1

In reference to this answer, you can get the bitmap from a file stream and dispose it before changing the image:

        Bitmap bitMapImage;
        using (var fs = new System.IO.FileStream(file, System.IO.FileMode.Open))
        {
            bitMapImage = new Bitmap(fs);
        }

        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);           

        bitMapImage.Save(file, ImageFormat.Jpeg); 
Community
  • 1
  • 1
KMoussa
  • 1,568
  • 7
  • 11