Search code examples
c#wpfbitmapsource

WPF: How to rotate a BitmapSource by any angle


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


Solution

  • 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.