Overwriting an image file (bitmap)

柔情痞子 提交于 2019-12-11 04:54:38

问题


Hello I am trying to save a bitmap image in a basic image editor program.

Here's the code:

         // then save it
        ImageBoxInApp.Image.Save(filename);

[EDIT] And I am opening the image with this

openFileDialog1.Title = "Select an Image";
        openFileDialog1.Filter = "All Files|*.*|Windows Bitmaps|*.bmp|JPEG Files|*.jpg";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            filename = openFileDialog1.FileName;
            Image img = System.Drawing.Image.FromFile(filename);

So when I try this I receive a Generic GDI+ error. So I found a solution to this and it looks like this:

        // Delete existing file first
        System.IO.File.Delete(filename);
        // then save it
        ImageBoxInApp.Image.Save(filename);

But when I try to do this I receive another error saying that the file I am deleting is currently open. This is because that is the file that I am trying to edit.

How do I "close" the file without actually closing the application? Or is there an alternative solution?

Thanks!


回答1:


Its hard to say without seeing some context around how your loading the file, but here are a couple of suggestions:

  1. Before saving, copy the existing image into a new Image, close the original, perform the delete, and save the copy.
  2. Save the file to a random filename, delete the original, rename the randomly named file to the original name.
  3. Load the file into a memory stream and use the in memory copy to initialize the image.

I'd personally go with option #3 for most cases. Be sure to dispose of the image when you've finished using it - it is best if you can wrap it in a using ( ) block.



来源:https://stackoverflow.com/questions/838063/overwriting-an-image-file-bitmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!