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
SetApartmentState(ApartmentState.STA)
on the thread that runs your code. Note however that you would somehow have to calculate the correct size of the resultimg bitmap. Otherwise parts of the source bitmap may be cut off. Moreover, you probably want to rotate around the image center, so you should setimage.RenderTransformOrigin = new Point(0.5, 0.5)
. Finally, a layout must be done on the Canvas, i.e. you have to call itsMeasure
andArrange
methods. – ElaneFreeze()
on the result bitmap to make it accessible across threads. – Elane