/// <summary> /// Applies the pixelate effect in given frame. /// </summary> /// <param name="image">The image to pixelate.</param> /// <param name="rectangle">The area to pixelate.</param> /// <param name="pixelateSize">The size of the pixel.</param> /// <param name="useMedian">Calculate the median color of the pixel block.</param> /// <returns>A pixelated Bitmap.</returns> public static BitmapSource Pixelate(BitmapSource image, Int32Rect rectangle, int pixelateSize, bool useMedian) { var croppedImage = new CroppedBitmap(image, rectangle); var pixelUtil = new PixelUtil(croppedImage); pixelUtil.LockBits(); //Loop through all the blocks that should be pixelated. for (var xx = 0; xx < croppedImage.PixelWidth; xx += pixelateSize) { for (var yy = 0; yy < croppedImage.PixelHeight; yy += pixelateSize) { var offsetX = pixelateSize / 2; var offsetY = pixelateSize / 2; if (xx + offsetX >= croppedImage.PixelWidth) { offsetX = croppedImage.PixelWidth; } if (yy + offsetY >= croppedImage.PixelHeight) { offsetY = croppedImage.PixelHeight; } //Get the pixel color in the center of the soon to be pixelated area. var pixel = useMedian ? pixelUtil.GetMedianColor(xx, yy, offsetX, offsetY) : pixelUtil.GetPixel(xx + offsetX, yy + offsetY); //For each pixel in the pixelate size, set it to the center color. for (var x = xx; x < xx + pixelateSize && x < croppedImage.PixelWidth; x++) { for (var y = yy; y < yy + pixelateSize && y < croppedImage.PixelHeight; y++) { pixelUtil.SetPixel(x, y, pixel); } } } } return(pixelUtil.UnlockBits()); }