Problems Overwriting (Re-Saving) Image When It Was Set as Image Source

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

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;

Overwrite Existing Image

You must remove your image if that is already exists.

private void saveImage()
{
Bitmap bmp1 = new Bitmap(pictureBox.Image);

if(System.IO.File.Exists("c:\\t.jpg"))
System.IO.File.Delete("c:\\t.jpg");

bmp1.Save("c:\\t.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
// Dispose of the image files.
bmp1.Dispose();
}

updating an image in an image control

thank you all for your input coz through them i finally figure a way around this. so my xaml still remains bound as <Image Source="{Binding Chart}" Margin="0 0 0 0"/> but in the code behind i changed the class property chart to return a bitmap as shown below:

  private BitmapImage image = null;

public BitmapImage Chart
{
get
{
return image;
}
set
{
if (value != image)
{
image = value;
NotifyPropertyChanged("Chart");

}

}
}

this class mind you implements INotifyPropertyChanged . at the point where i set the image i am now using this code:

BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
//in the following code path is a string where i have defined the path to file
img.UriSource = new Uri(string.Format("file://{0}",path));
img.EndInit();
c.Chart = img;

this works well for me and refreshes the image upon update.

Image file locked after loading in WPF

dlev had a good advice. Here you see the cache option that should solve it: Problems overwriting (re-saving) image when it was set as image source

imgTemp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;


Related Topics



Leave a reply



Submit