/// <summary> /// Rotates the bitmap in 90° steps clockwise and returns a new rotated WriteableBitmap. /// </summary> /// <param name="bmp">The WriteableBitmap.</param> /// <param name="angle">The angle in degrees the bitmap should be rotated in 90° steps clockwise.</param> /// <returns>A new WriteableBitmap that is a rotated version of the input.</returns> public static BitmapBuffer Rotate(this BitmapBuffer bmp, int angle) { using (var context = bmp.GetBitmapContext(ReadWriteMode.ReadOnly)) { // Use refs for faster access (really important!) speeds up a lot! int w = context.Width; int h = context.Height; int[] p = context.Pixels; int i = 0; BitmapBuffer result; angle %= 360; if (angle > 0 && angle <= 90) { result = BitmapBufferFactory.New(h, w); using (var destContext = result.GetBitmapContext()) { var rp = destContext.Pixels; for (int x = 0; x < w; x++) { for (int y = h - 1; y >= 0; y--) { int srcInd = y * w + x; rp[i] = p[srcInd]; i++; } } } } else if (angle > 90 && angle <= 180) { result = BitmapBufferFactory.New(w, h); using (var destContext = result.GetBitmapContext()) { var rp = destContext.Pixels; for (int y = h - 1; y >= 0; y--) { for (int x = w - 1; x >= 0; x--) { int srcInd = y * w + x; rp[i] = p[srcInd]; i++; } } } } else if (angle > 180 && angle <= 270) { result = BitmapBufferFactory.New(h, w); using (var destContext = result.GetBitmapContext()) { int[] rp = destContext.Pixels; for (int x = w - 1; x >= 0; x--) { for (int y = 0; y < h; y++) { int srcInd = y * w + x; rp[i] = p[srcInd]; i++; } } } } else { result = bmp.Clone(); } return(result); } }