我有一个包含图像控件的视图。
<Image
x:Name="img"
Height="100"
Margin="5"
Source="{Binding Path=ImageFullPath Converter={StaticResource ImagePathConverter}}"/>
绑定使用的转换器没有太多有趣的操作,只是将
BitmapCacheOption
设置为"OnLoad",这样当我尝试旋转文件时,该文件就会被解锁。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;
}
这里是旋转图像的代码。
val
始终为90或-90,path
是我想要旋转的.tif
文件的完整路径。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);
}
}
我遇到的问题是,当我将
BitmapCacheOption
设置为BitmapCacheOption.OnLoad
时,文件没有被锁定,但旋转并不总是旋转图像(我认为每次都使用原始缓存值)。如果我使用BitmapCacheOption.OnLoad,以便文件未被锁定,那么在图像旋转后如何更新图像控件?原始值似乎被缓存在内存中。
是否有更好的替代方法来旋转当前在视图中显示的图像?