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
312 views
in Technique[技术] by (71.8m points)

c# - Problems overwriting (re-saving) image when it was set as image source

Good day all,

I am having some trouble with image permissions.

I am loading an image from file, resizing it and then saving it out to another folder. I am then displaying this like so:

    uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);

    imgAsset.Source = new BitmapImage(uriSource);

This is working fine, the trouble comes if the user then selects another image immediately after and tries to save it over the original file.

An exception is generated upon saving my image "ExternalException: A generic error occurred in GDI+."

After some playing around i have narrowed the error down to imgAsset.Source = new BitmapImage(uriSource); as removing this line and not setting the imagesource will allow me to overwrite this file many times.

I have also tried setting the source to something else, before re-saving in the hope that the old reference would be disposed, this was not the case.

How can i get past this error?

Thanks, Kohan

Edit

Now using this code i am not getting the exception however the image source is not updating. Also since i am not using a SourceStream, im not sure what i need to dispose of to get this working.

       uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);

       imgTemp = new BitmapImage();
       imgTemp.BeginInit();
       imgTemp.CacheOption = BitmapCacheOption.OnLoad;
       imgTemp.UriSource = uriSource;
       imgTemp.EndInit();

       imgAsset.Source = imgTemp;
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're almost there.

  • Using BitmapCacheOption.OnLoad was the best solution to keep your file from being locked.

  • To cause it to reread the file every time you also need to add BitmapCreateOptions.IgnoreImageCache.

Adding one line to your code should do it:

  imgTemp.CreateOption = BitmapCreateOptions.IgnoreImageCache;

thus resulting in this code:

  uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);
  imgTemp = new BitmapImage();
  imgTemp.BeginInit();
  imgTemp.CacheOption = BitmapCacheOption.OnLoad;
  imgTemp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
  imgTemp.UriSource = uriSource;
  imgTemp.EndInit();
  imgAsset.Source = imgTemp;

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

...