Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asp.net - C# :GDI+ : OverWriting an Image using Save Method of Bitmap

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. Any idea how to 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.,other wose it will.But i want to have the same name .Any thought ?? ? Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...