title: WPF - Rotate and Save Image -both for the View and to Disk
body: <p>I have a View that contains an image control.</p>
  
  <pre><code>&lt;Image
  x:Name="img"
  Height="100"
  Margin="5"
  Source="{Binding Path=ImageFullPath Converter={StaticResource ImagePathConverter}}"/&gt;
  </code></pre>
  
  <p>The binding uses a converter that does nothing interesting except set <code>BitmapCacheOption</code> to "OnLoad", so that the file is unlocked when I attempt to rotate it.</p>
  
  <pre><code>public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
      // value contains the full path to the image
      string val = (string)value;
  
      if (val == null)
          return null;
  
      // load the image, specify CacheOption so the file is not locked
      BitmapImage image = new BitmapImage();
      image.BeginInit();
      image.CacheOption = BitmapCacheOption.OnLoad;
      image.UriSource = new Uri(val);
      image.EndInit();
  
      return image;
  }
  </code></pre>
  
  <p>Here is my code to rotate the image. <code>val</code> is always 90 or -90, and <code>path</code> is the full path to the <code>.tif</code> file I want to rotate. </p>
  
  <pre><code>internal static void Rotate(int val, string path)
  {
      //cannot use reference to what is being displayed, since that is a thumbnail image.
      //must create a new image from existing file. 
      Image image = new Image();
      BitmapImage logo = new BitmapImage();
      logo.BeginInit();
      logo.CacheOption = BitmapCacheOption.OnLoad;
      logo.UriSource = new Uri(path);
      logo.EndInit();
      image.Source = logo;
      BitmapSource img = (BitmapSource)(image.Source);
  
      //rotate tif and save
      CachedBitmap cache = new CachedBitmap(img, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
      TransformedBitmap tb = new TransformedBitmap(cache, new RotateTransform(val));
      TiffBitmapEncoder encoder = new TiffBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(tb)); //cache
      using (FileStream file = File.OpenWrite(path))
      {
          encoder.Save(file);
      }
  }
  </code></pre>
  
  <p>The issue I am experiencing is when I get the <code>BitmapCacheOption</code> to <code>BitmapCacheOption.OnLoad</code>, the file is not locked however rotate does not always rotate the image (I believe it is using the original cached value each time).</p>
  
  <p>If I use BitmapCacheOption.OnLoad so the file is not locked, how can I update the Image control once the image has been rotated? The original value seems to be cached in memory.</p>
  
  <p>Is there a better alternative for rotating an image that is currently being displayed in the view?</p>