Overwriting an image using save method of bitmap

asp.net, gdi+

Solution

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.

Problem

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 trying to save with the existing name, Save method is throwing an error. But if I give a different name it is getting saved. But I want to have the same file name for the newly created resized image as I need to overwrite the existing file with the new file which is resized. How can I go ahead? My code is: ``` oldImagePath= oldImagePath.Replace(".jpg", "NEW.jpg"); try { ImageCodecInfo[] Info = ImageCodecInfo.GetImageEncoders(); EncoderParameters Params = new EncoderParameters(1); Params.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); target.Save(oldImagePath, Info[1], Params); } ``` If I comment the first line which creates a new name for the destination file, it will not work, otherwise it will. But I want to have the same name. How can I achieve that?

Original source