0

I'm making an app that adds (draws) some text on an image stored initially in a file. I managed to modify the image and save it in another file, but I'm trying not to create a second file, but store the result in the original file, although when I try to do that, as said in the Microsoft documentation website, that will result in an Exception being thrown (because the Image.Save method does not allow to write in the same file the image was created from). Is there a way to do it properly?

Right now I've made a workaround, saving the modified image into another file, and then I deleting it and changing the name of the second file to the original one.

Here's my code.

Image image = Image.FromFile(originalFile);
Graphics graphics = Graphics.FromImage(image);
...
graphics.DrawString(line, ...);
...
image.Save(newFile);
graphics.Dispose();
image.Dispose();
File.Delete(originalFile);
File.Move(newFile, originalFile);
Eequiis
  • 149
  • 10
  • 1
    I think it's probably a reasonable solution; if you think about it saving a new image over the top of the old one is virtually the same set of operations as this anyway. You could read the file into a byte array and the load it from a memory stream but possibly writing a new file allows windows to keep the disk defragmented better anyway because it can hunt for contiguous space in which to put the new file then release the old – Caius Jard Jun 08 '20 at 09:54
  • Perhaps you can open the image from a stream using the `FileAccess.ReadWrite` option – xdtTransform Jun 08 '20 at 09:55
  • Related: [IOException: The process cannot access the file 'file path' because it is being used by another process](https://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being). More general not about image loading via `Image.FromFile(string path)`. – xdtTransform Jun 08 '20 at 09:57
  • Does this answer your question? [How can I open an image and edit the image with C# .Net Compact Framework.](https://stackoverflow.com/questions/18890964/how-can-i-open-an-image-and-edit-the-image-with-c-sharp-net-compact-framework) – xdtTransform Jun 08 '20 at 09:58
  • Moving `graphics.Dispose();` before `image.Save(originalFile);` should fix the issue but a using is clearer. – xdtTransform Jun 08 '20 at 10:01

1 Answers1

2

The docs for Image.FromFile do say "The file remains locked until the Image is disposed."

Your method is fine (though File.Replace would probably be better than deleting and moving).

If you do want to unlock the file earlier, another option would be to clone the image once it's opened, dispose of the "file-backed" image, and use that image for your drawing.

AKX
  • 152,115
  • 15
  • 115
  • 172