概述Identicon 是 Don Park 在2007年首次想出的。也許有些人對“Identicon”這詞比較陌生,其實大家都認識的——就是在GitHub、Stack Overflow、V2EX還有Slack上的那種看似隨機又有規律還不重樣的默認頭像。一般的,如果你在一個網站注冊后沒有指定自己的頭像,網站會使用 Gravatar 或者 Identicon 作為你的默認頭像。Gravatar 大多都是千篇一律,Identicon 卻千姿百態。
          原理wiki 上說,最初的 Identicon,通常是將用戶的IP地址哈希成可視化的,由9塊圖像構成的圖形,服務器通過 Identicon,就能夠以頭像的形式來分辨用戶,這種方法同時也能保護用戶的隱私。后來,由第三方將其表現形式擴展至了各種圖形,于是就有了大家看到的不同風格的 Identicon 頭像。
          實現拿 Github 來說吧,在 GitHub 的 Blog 上有對 Identicon 過程做了簡單的介紹,他們是將用戶的ID取哈希值,然后根據哈希值每一位的奇偶來決定對應位置上的像素的開關。這樣生成 的圖像,配上由哈希值決定的顏色,保證可生成大量獨一無二的圖像。有個 Mathematica 的實現,感興趣的戳。

          附Bitmap實現代碼
          public BitmapSource GenerateIdenticon(Object value)
          {
              int width = 9;
              int height = width;
              int stride = (PixelFormats.Indexed8.BitsPerPixel * width) / 8;
              byte[] pixels = new byte[height * stride];
              int hash = value.GetHashCode();
           
              BitmapPalette myPalette = new BitmapPalette(new Color[] { Colors.White, Colors.LightGray, Colors.LightSeaGreen, Colors.White });
           
              for (int y = 0; y < 5; ++y)
               for (int x = y; x < 5; ++x)
               {
                   byte color = (byte)(hash & 0x03);
                  hash >>= 2;
           
                  // II quadrant
                  pixels[x + (y * stride)] = color;
                  pixels[y + (x * stride)] = color;
           
                  // I quadrant
                  pixels[(8 - x) + (y * stride)] = color;
                  pixels[(8 - y) + (x * stride)] = color;
           
                  // III quadrant
                  pixels[x + ((8 - y) * stride)] = color;
                  pixels[y + ((8 - x) * stride)] = color;
           
                  // IV quadrant
                  pixels[(8 - x) + ((8 - y) * stride)] = color;
                  pixels[(8 - y) + ((8 - x) * stride)] = color;
               }
           
              return BitmapSource.Create(width, height, 96, 96, PixelFormats.Indexed8, myPalette, pixels, stride);
          }
          posted on 2018-05-19 10:33 Ying-er 閱讀(771) 評論(0)  編輯  收藏 所屬分類: .Net
          主站蜘蛛池模板: 甘洛县| 监利县| 梁河县| 吉木乃县| 玛沁县| 库伦旗| 子长县| 梅河口市| 遂川县| 四川省| 拉萨市| 蒲江县| 英德市| 阿克陶县| 微博| 施秉县| 融水| 晴隆县| 洛阳市| 苍山县| 葫芦岛市| 同心县| 自贡市| 安乡县| 健康| 垫江县| 承德县| 武穴市| 尼勒克县| 桐乡市| 昭觉县| 澳门| 定远县| 鄂尔多斯市| 德江县| 定西市| 河间市| 固安县| 运城市| 嘉祥县| 肇源县|