WPF - 旋转并保存图像 - 视图和磁盘

时间:2010-04-27 17:23:55

标签: wpf image controls rotation bitmapimage

我有一个包含图像控件的视图。

<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这样文件没有锁定,那么一旦图像旋转后如何更新Image控件?原始值似乎缓存在内存中。

是否有更好的选择来旋转当前在视图中显示的图像?

1 个答案:

答案 0 :(得分:0)

又一年后,我需要这样做,并找到了following solution

如果您有图片元素:

<grid>
    <stackpanel>
        <Image Name="img" Source="01.jpg"/>
        <Button Click="Button_Click" Content="CLICK"/>
    </stackpanel>
</grid>

您可以在代码隐藏中对其进行旋转:

private double rotateAngle = 0.0;
private void RotateButton_Click(object sender, RoutedEventArgs e)
{
    img.RenderTransformOrigin = new Point(0.5, 0.5);
    img.RenderTransform = new RotateTransform(rotateAngle+=90);
}

或者,假设您的图片元素称为img

private double RotateAngle = 0.0;
private void Button_Click(object sender, RoutedEventArgs e)
{
    TransformedBitmap TempImage = new TransformedBitmap();

    TempImage.BeginInit();
    TempImage.Source = MyImageSource; // MyImageSource of type BitmapImage

    RotateTransform transform = new RotateTransform(rotateAngle+=90);
    TempImage.Transform = transform;
    TempImage.EndInit();

    img.Source = TempImage ;
}