Domanda

I am developing a WPF application, a messenger client. The user should be able to change his avatar image. When he right-clicks his avatar, a open file dialog appears and there he can select the image he wants. After he has made his decision I delete his current avatar and copy the new one in the same place with the same name. The avatar image is a rectangle with an imagebrush fill. The problem is that the image does not update until I restart the application. Here is the piece of code used to load the new image.

if (x.ShowDialog() == true)
{
    ImageBrush img = new ImageBrush();
    BitmapImage bit = new BitmapImage();
    Bitmap bmp = new Bitmap(x.FileName);
    System.IO.File.Delete(System.IO.Directory.GetCurrentDirectory() + "/data/images/avatar/x.png");
    bmp.Save(System.IO.Directory.GetCurrentDirectory() + "/data/images/avatar/x.png", System.Drawing.Imaging.ImageFormat.Png);

    bit.BeginInit();
    bit.CacheOption = BitmapCacheOption.OnLoad;
    bit.UriSource = new Uri(@"pack://siteoforigin:,,,/data/images/avatar/x.png");
    bit.EndInit();
    img.ImageSource = bit;
    ProfileImage.Fill = img;
}

I hope you can help me solve this issue or offer me some alternatives. Thank you all!

È stato utile?

Soluzione

In order to make BitmapImage reload the image file (with identical file path), you could set the BitmapCreateOptions.IgnoreImageCache option:

bit.BeginInit();
bit.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bit.CacheOption = BitmapCacheOption.OnLoad;
bit.UriSource = new Uri(@"pack://siteoforigin:,,,/data/images/avatar/x.png");
bit.EndInit();
img.ImageSource = bit;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top