skhurams skhurams - 8 days ago 6
C# Question

drawing string on image and save with same name c#

hi im 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 saveing it says file is already in use by other program and if i overrite its 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);

Answer

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