1

What I am trying to do is save a picture from a webcam which is attached to my computer, write a string on top of that picture, and save the file. The way my program runs is first it takes a picture, and then I want to be able to write on top of it. Here is the code I have so far to write on top of my saved image, but it throws an 'ExternalException'.

Bitmap myBitmap = new Bitmap("C:\\Users\\me\\Desktop\\CamApp\\" + filename + ".jpeg");
Graphics g = Graphics.FromImage(myBitmap);
g.DrawString("HELLO", new Font("Tahoma", 40), Brushes.White, new PointF(0, 0));
myBitmap.Save("C:\\Users\\me\\Desktop\\CamApp\\" + filename + ".jpeg",
    System.Drawing.Imaging.ImageFormat.Jpeg);

Thanks in advance.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
AlvinJ
  • 261
  • 4
  • 7
  • 20

1 Answers1

2

The problem you are seeing is discussed in this other question: Free file locked by new Bitmap(filePath)

When you use the Bitmap constructor that takes a filename, the file is locked until the Bitmap is disposed. This keeps you from overwriting that image file.

You can use @Brian's answer on the question above to load a Bitmap without leaving the file locked: https://stackoverflow.com/a/14837330/34208

Once you load the image using this method, you'll be able to save over the original file.

Edit with code sample:

Replace your line...

Bitmap myBitmap = new Bitmap("C:\\Users\\me\\Desktop\\CamApp\\" + filename + ".jpeg");

with

Bitmap myBitmap = FromFile(@"C:\Users\me\Desktop\CamApp\" + filename + ".jpeg");

and make sure to copy over the FromFile method from the linked answer.

Community
  • 1
  • 1
David
  • 34,223
  • 3
  • 62
  • 80
  • Thanks for the answer. So I understand that the file is locked but I am confused as to how I would use this method in my code. Do I do something along the lines of: 'Bitmap myBitmap = new Image(src)' – AlvinJ Apr 02 '14 at 20:44