WPF - Rotate and Save Image - For Preview And To Disk

I have a view that contains an image control.

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

      

Linking uses a converter that does nothing interesting except set BitmapCacheOption

to "OnLoad" so that the file is unlocked when I try 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 for rotating an image. val

always 90 or -90, and path

is the full path to the file .tif

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 problem I am facing is when I get BitmapCacheOption

to BitmapCacheOption.OnLoad

, the file is not locked, but the rotation does not always rotate the image (I believe it uses the original cached value every time).

If I use BitmapCacheOption.OnLoad so the file is not locked, how can I update the Image control after rotating the image? The original value seems to be cached in memory.

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

+2


a source to share





All Articles