Generating Identicons

November 2013 ยท 2 minute read

Identicons are icons that are generated from some form of user information. They usually serve to fill the gaps left by photo-less users that don’t provide a photo as unique(ish) identifiers for users.

These are usually generated by hashing the chosen user data and then using that hash to flip image pixels on and off. The following code snippit is a Java implementation of this concept and generates a 5*5 pixel, horizontally symmetrical identicon much like the ones github recently rolled out.

byte[] hash = MessageDigest.getInstance(algorithim).digest(userName.getBytes());

BufferedImage identicon = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    WritableRaster raster = identicon.getRaster();

    int [] background = new int [] {255,255,255, 0};
    int [] foreground = new int [] {hash[0] & 255, hash[1] & 255, hash[2] & 255, 255};

    for(int x=0 ; x < width ; x++) {
            //Enforce horizontal symmetry
            int i = x < 3 ? x \: 4 - x;
    	for(int y=0 ; y < height; y++) {
    		int [] pixelColor;
		//toggle pixels based on bit being on/off
    		if((hash[i] >> y & 1) == 1)
    		      pixelColor = foreground;
    		      pixelColor = background;
    		raster.setPixel(x, y, pixelColor);

    return identicon;

For an android version of this code you can take a look at the source code of my Android Contact Identicons app that generates these types of identicons for contact photos.