아바타 제너레이터

각 사용자의 고유 이미지 아바타를 생성하는 기능에 대해 서술한다.

아이디어 개요

Github나 간혹 특정 사이트를 확인해보면, 아래처럼 계정마다 프로필 이미지가 생성되어 있는 경우가 있다. 흥미로운 점은 이것이 랜덤으로 생성되는 것이 아니라, 각 ID마다 고유한 이미지를 생성한다는 점이다.

오픈소스 출처

동작원리

아바타 제너레이터는 해시(Hash) 알고리즘을 이용한 각 데이터에 대한 고유 값으로 각 ID별로 고유한 이미지를 생성하는 기법이다.

  1. 사용자의 ID를 MD5 해쉬 알고리즘으로 변환한다.

  2. 해당 바이트 값을 순서대로 읽어들여 주어진 규칙에 맞춰 이미지를 생성한다.

  3. 생성된 이미지는 SVG를 통해 HTML에 삽입한다.

function(){
            var image      = this.image(),
                size       = this.size,
                baseMargin = Math.floor(size * this.margin),
                cell       = Math.floor((size - (baseMargin * 2)) / 5),
                margin     = Math.floor((size - cell * 5) / 2),
                bg         = image.color.apply(image, this.background),
                fg         = image.color.apply(image, this.foreground);

            // the first 15 characters of the hash control the pixels (even/odd)
            // they are drawn down the middle first, then mirrored outwards
            var i, color;
            for (i = 0; i < 15; i++) {
                color = parseInt(this.hash.charAt(i), 16) % 2 ? bg : fg;
                if (i < 5) {
                    this.rectangle(2 * cell + margin, i * cell + margin, cell, cell, color, image);
                } else if (i < 10) {
                    this.rectangle(1 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);
                    this.rectangle(3 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);
                } else if (i < 15) {
                    this.rectangle(0 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);
                    this.rectangle(4 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);
                }
            }
function rectangle(x, y, w, h, color, image){
            if (this.isSvg()) {
                image.rectangles.push({x: x, y: y, w: w, h: h, color: color});
            } else {
                var i, j;
                for (i = x; i < x + w; i++) {
                    for (j = y; j < y + h; j++) {
                        image.buffer[image.index(i, j)] = color;
                    }
                }
            }
        }

Last updated

Was this helpful?