//Karthik Srinivasan

Product Engineer, CTO & a Beer Enthusiast
Experiments, thoughts and scripts documented for posterity.

Quirky Personal Projects

LinkedIn

Email me

Generating Image mosaics for fun

March 19, 2018

LOADING.....


The idea behind building image mosaic is to take the original image and split it to a grid say 20x20 pixels (depending on the size of the image) and compute the average RGB within each of the blocks.



Since we are splitting the image into square Grid, the thumbnails had to be resized to be uniform. Once the thumbnails were resized, their average RGB values were calculated. Average color code snippet:
    Point end = new Point(area.X + area.Width, area.Y + area.Height);

    for (int x = area.X = 0; x < end.X; x += quality) {
     for (int y = area.Y; y < end.Y; y += quality) {
      c = bmp.GetPixel(x, y);
      r += c.R;
      g += c.G;
      b += c.B;
      p++;
     }
    }
    return Color.FromArgb(255, (int)(r / p), (int)(g / p), (int)(b / p));


The next step was to iterate through each image and find the closest match to each block on the image. Since the image grid is basically a matrix of n x m, this can be serialized and stored in file/db. Following class model to store the matrix:
    public class MosaicTile
    {
        public int X { get; set; }
        public int Y { get; set; }
        public string ImageFileName { get; set; }
    }
Upon page load, the browser builds a table/grid and places the image in the appropriate location (x,y) to make it look like a single mosaic. As a side note, since the browser displays 100's of images for the mosaic, this potentially could lead to memory build up on the browser. This can be handled by using revokeObjectURL method. Code snippet:

    $('img').load(function () {
        window.URL.revokeObjectURL($(this).attr('src'));
    });

Library for generating image mosaic in c# can be found at my github repo : https://github.com/karthik20522/ImageMosaic