PixelateEffect

Feb 28, 2012 at 3:19 PM

public class PixelateEffect : IEffect
    {
        public string Name { get { return "Pixelate"; } }

        public PixelateEffect()
        {

        }

        /// <summary>
        /// Processes a bitmap and returns a new processed WriteabelBitmap.
        /// </summary>
        /// <param name="input">The input bitmap.</param>
        /// <returns>The result of WriteabelBitmap processing.</returns>
        public WriteableBitmap Process(WriteableBitmap input)
        {
            // Prepare some variables
            var width = input.PixelWidth;
            var height = input.PixelHeight;
            return Process(input.Pixels, width, height, 100).ToWriteableBitmap(width, height);
        }

        public int[] Process(int[] inputPixels, int width, int height)
        {
            return this.Process(inputPixels, width, height, 10);
        }

        public int[] Process(int[] inputPixels, int width, int height, int blockSize)
        {
            // y, x
            int[,] pixelated = inputPixels.To2DArray(width, height);

            // Loop across 2D array
            for (int bX = 0; bX < width; bX += blockSize)
            {
                for (int bY = 0; bY < height; bY += blockSize)
                {
                    // Find adjusted block width
                    int blockX = bX + blockSize <= width ? blockSize : width - bX;
                    int blockY = bY + blockSize <= height ? blockSize : height - bY;

                    // Get centre colour
                    int pixel = pixelated[bY + blockY / 2, bX + blockX / 2];

                    // Apply colour to block
                    for (int x = bX; x < bX + blockX; x++)
                        for (int y = bY; y < bY + blockY; y++)
                            pixelated[y, x] = pixel;
                }
            }

            return pixelated.ToArray();
        }
    }