将图像设置为图像源时覆盖

将图像设置为图像源时覆盖

本文介绍了将图像设置为图像源时覆盖(重新保存)图像的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
解决方案

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;

这篇关于将图像设置为图像源时覆盖(重新保存)图像的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:06