Example #1
0
        /// <summary>
        /// Renders a pixelated version of <see cref="originalImage"/>. If <paramref name="renderGrid"/> is true, a grid will be drawn over the image.
        /// </summary>
        /// <param name="renderGrid"></param>
        /// <returns>The pixelated version of the image.</returns>
        private Image RenderImage(bool renderGrid = true)
        {
            if (originalImage as Bitmap == null)
            {
                return(null);
            }

            Bitmap source     = originalImage as Bitmap;
            Bitmap rasterized = new Bitmap(originalImage.Width, originalImage.Height);
            int    gridSize   = tbGridSize.Value;

            //Well keep a list of rectangles per color, so we can show the usage count of each color,
            //but this also enables us to draw all rectangles of the same color in one operation.
            drawList = new Dictionary <Color, List <Rectangle> >();

            for (int x = 0; x < rasterized.Width; x += gridSize)
            {
                for (int y = 0; y < rasterized.Height; y += gridSize)
                {
                    int width = gridSize, height = gridSize;

                    //Fix width or height if the image is not divided in squares (near the edges)
                    if (x + gridSize >= rasterized.Width)
                    {
                        width = (rasterized.Width) - x - 1;
                    }

                    if (y + gridSize >= rasterized.Height)
                    {
                        height = (rasterized.Height) - y - 1;
                    }

                    Rectangle block = new Rectangle(x, y, width, height);
                    Color     pixel = interpolator.DetermineColor(source, block);

                    if (!drawList.ContainsKey(pixel))
                    {
                        drawList.Add(pixel, new List <Rectangle>());
                    }

                    drawList[pixel].Add(block);
                }
            }

            using (Graphics g = Graphics.FromImage(rasterized)) {
                //Using each color, draw the list of rectangles at once
                foreach (Color key in drawList.Keys)
                {
                    using (Brush b = new SolidBrush(key))
                        g.FillRectangles(b, drawList[key].ToArray());
                }

                if (renderGrid)
                {
                    //Draw horizontal lines
                    for (int x = gridSize; x < rasterized.Width; x += gridSize)
                    {
                        g.DrawLine(Pens.Black, x, 0, x, rasterized.Height);
                    }

                    //Draw vertical lines
                    for (int y = gridSize; y < rasterized.Height; y += gridSize)
                    {
                        g.DrawLine(Pens.Black, 0, y, rasterized.Width, y);
                    }
                }
            }

            return(rasterized);
        }