C# :GDI+ : OverWriting an Image using Save Method of Bitmap

后端 未结 2 1878
再見小時候
再見小時候 2020-12-20 16:30

I have an ASP.NET C# page where i am resizing the images in a folder .I am using GDI+ to do this.I want to resize the images and replace with the old images.So when i am try

相关标签:
2条回答
  • 2020-12-20 17:03

    You need to delete the original file first. It is important to make the distinction - when you are working with image manipulation in .NET, you are working with an in-memory object whose bytes were populated by reading the original image. You are not working with the actual original image. So when you go to save this entirely new object (which happens to use data from an existing image), and you try to use an already in-use path, you will get an exception.

    You also need to make sure the original file is not still open at this point; make sure to dispose of the original file stream you used to populate the Image object you're manipulating. Then delete, then save.

    0 讨论(0)
  • 2020-12-20 17:17

    If you load an image using the technique in the following line

     Image imgPhoto = Image.FromFile("myphoto.jpg");
    

    then this keeps a handle open to the file so when you attempt to overwrite it the file is still currently in use and so you are unable to write to it.

    To get around this, if you load the file into a stream then this allows you to overwrite the original file as the file handle has been freed as the image information has been written to memory.

    You can do this in the following way:

    FileStream fs = new FileStream("myphoto.jpg", FileMode.Open);
    Image imgPhoto = Image.FromStream(fs);
    fs.Close();
    
    0 讨论(0)
提交回复
热议问题