Rotate and Save Image - C#
- by Taylor
Hello, I'm trying to rotate and save an image, along with returning a BitmapSource.
I pass in the rotation value (90 or -90) and the full path to the image I want to rotate to the method shown here. It works fine if I start and stop my application between calling this method. however, if the application calls rotate multiple times the rotate only happens once. I know the original image must be cached in memory, because if I pass values 90, 180, 270 I see the rotations work. I want to be able to pass in a value of 90 or -90 and have that rotate and save the original image.
How can I make the rotate work for each call? Is there a way to clear the cached value of the image? If I don't set the BitmapCacheOption to OnLoad, I am unable to transform and save the image since the image is "being used by another process".
public BitmapImage Rotate(int val, string path)
{
//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 image 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));
using (FileStream file = File.OpenWrite(path))
{
encoder.Save(file);
}
//update page view
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri(path);
bi.EndInit();
return bi;
}