views:

319

answers:

0

Hello, I have a View that contains an image control.

           <Image
           x:Name="img"
           Height="100"
           Margin="5"
           Source="{Binding Path=ImageFullPath Converter={StaticResource ImagePathConverter}}"/>

The binding uses a converter does nothing interesting except set BitmapCacheOption to "OnLoad", so that the file is unlocked when I attempt to rotate it.

 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;
    }

Here is my code to rotate the image. val is always 90 or -90, and path is the full path to the .tif file I want to rotate.

 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);
        }
    }

The issue I am experiencing is when I get the BitmapCacheOption to BitmapCacheOption.OnLoad, the file is not locked however rotate does not always rotate the image (I believe it is using the original cached value each time).

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)

Is there a better alternative for rotating an image that is currently being displayed in the view?