问题
Ok, I tried this:
TransformedBitmap tbm = new TransformedBitmap(myBitmapSource, new RotateTransform(angle));
return tbm;
But this does not work with angles other than multiples of 90degrees.
New I tried to use a RenderTargetBitmap:
var image = new Canvas();
image.Width = myBitmapSource.PixelWidth;
image.Height = myBitmapSource.PixelHeight;
image.Background = new ImageBrush(myBitmapSource);
image.RenderTransform = new RotateTransform(angle);
RenderTargetBitmap rtb = new RenderTargetBitmap(myBitmapSource.PixelWidth, myBitmapSource.PixelHeight, myBitmapSource.DpiX, myBitmapSource.DpiY, myBitmapSource.Format);
rtb.Render(image);
return rtb;
But this gives me:
"The calling thread must be STA, because many UI components require this."
This runs in a service without a GUI.
Can somebody give me a working code sample on how to rotate a BitmapSource in WPF (without a GUI) by any angle?
update:
Vote for feature request: http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/10870098-allow-rotation-of-bitmapsource-by-any-angle
回答1:
Well you can run that code in a separate thread. Just set the single-threaded apartment (STA).
Thread thread = new Thread(DoTheRotation);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
Code for rotation in a method called by the thread:
public void DoTheRotation()
{
var image = new Canvas();
image.Width = myBitmapSource.PixelWidth;
image.Height = myBitmapSource.PixelHeight;
image.Background = new ImageBrush(myBitmapSource);
image.RenderTransform = new RotateTransform(angle);
RenderTargetBitmap rtb = new RenderTargetBitmap(myBitmapSource.PixelWidth, myBitmapSource.PixelHeight, myBitmapSource.DpiX, myBitmapSource.DpiY, myBitmapSource.Format);
rtb.Render(image);
}
Then you just need to change the code to pass the object.
回答2:
just use a TransformedBitmap
var rotatedImage = new TransformedBitmap(image, new RotateTransform(180));
回答3:
Be aware that TransformedBitmap supports only orthogonal transforms such as rotation transforms of 90° increments and scale transforms. Transforms that skew the image are not supported. So for the rotation you can only use 90, 180, 270 degrees! As already mentioned in the original question!
来源:https://stackoverflow.com/questions/33914140/wpf-how-to-rotate-a-bitmapsource-by-any-angle