0

好的,我试过这个:

TransformedBitmap tbm = new TransformedBitmap(myBitmapSource, new RotateTransform(angle));
return tbm;

但这不适用于除 90 度的倍数以外的角度。

新我尝试使用 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;

但这给了我:

"The calling thread must be STA, because many UI components require this."

这在没有 GUI 的服务中运行。

有人可以给我一个关于如何在 WPF(没有 GUI)中以任何角度旋转 BitmapSource 的工作代码示例吗?

更新:

为功能请求投票:http: //visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/10870098-allow-rotation-of-bitmapsource-by-any-angle

4

3 回答 3

8

只需使用 TransformedBitmap

var rotatedImage = new TransformedBitmap(image, new RotateTransform(180));
于 2017-02-17T14:03:35.863 回答
2

好吧,您可以在单独的线程中运行该代码。只需设置单线程单元 (STA)。

Thread thread = new Thread(DoTheRotation);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

线程调用的方法中的旋转代码:

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);
}

然后你只需要更改代码来传递对象。

于 2015-11-25T11:07:42.583 回答
0

请注意,TransformedBitmap 仅支持正交变换,例如 90° 增量的旋转变换和缩放变换。不支持扭曲图像的变换。因此,对于旋转,您只能使用 90、180、270 度!正如原始问题中已经提到的!

于 2017-08-07T08:38:18.860 回答