Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Drawing;
- using System.Security.Cryptography;
- using System.Text;
- using System.Windows.Forms;
- namespace WindowsFormsApplication1
- {
- public sealed class Identicon : Control
- {
- public enum HashAlgorithms
- {
- MD5,
- SHA1,
- SHA256,
- SHA384,
- SHA512,
- RIPEMD160
- }
- private string Identity = string.Empty;
- private HashAlgorithms HashType = HashAlgorithms.SHA256;
- private Double Margin = .08;
- public Identicon()
- {
- if (string.IsNullOrEmpty(this.Identity))
- {
- this.Identity = Guid.NewGuid().ToString();
- }
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- var hash = this.HashString(this.Identity, this.HashType);
- var size = (this.Size.Width < this.Size.Height) ? this.Size.Width : this.Size.Height;
- var margin = Math.Floor(size*this.Margin);
- var cell = Math.Floor((size - (margin * 2)) / 5);
- var b = new Bitmap(this.Size.Width, this.Size.Height);
- var g = Graphics.FromImage(b);
- var hsl = new HSLColor(
- (Convert.ToInt32(hash.Substring(hash.Length - 7), 16) / 0xfffffff),
- .5,
- .7);
- var rgb = (Color)hsl;
- var bg = this.BackColor;
- var fg = rgb;
- for (var i = 0; i < 15; i++)
- {
- var color = (Convert.ToInt32(hash[i].ToString(), 16) % 2) == 1 ? bg : fg;
- if (i < 5)
- {
- Rectangle(2 * cell + margin, i * cell + margin, cell, cell, new SolidBrush(color), g);
- }
- if (i < 10)
- {
- this.Rectangle(1 * cell + margin, (i - 5) * cell + margin, cell, cell, new SolidBrush(color), g);
- this.Rectangle(3 * cell + margin, (i - 5) * cell + margin, cell, cell, new SolidBrush(color), g);
- }
- if (i < 15)
- {
- this.Rectangle(0 * cell + margin, (i - 10) * cell + margin, cell, cell, new SolidBrush(color), g);
- this.Rectangle(4 * cell + margin, (i - 10) * cell + margin, cell, cell, new SolidBrush(color), g);
- }
- }
- e.Graphics.DrawImage(b, new Point(0, 0));
- base.OnPaint(e);
- }
- private void Rectangle(double x, double y, double w, double h, SolidBrush color, Graphics g)
- {
- g.FillRectangle(color, new RectangleF((float)x, (float)y + ((this.Size.Width < this.Size.Height) ? this.Size.Width : this.Size.Height * 9 / 100), (float)w, (float)h));
- }
- private string HashString(string str, HashAlgorithms Algorithm)
- {
- var hasher = HashAlgorithm.Create(Algorithm.ToString());
- var strBytes = Encoding.UTF8.GetBytes(str);
- var hashed = hasher.ComputeHash(strBytes);
- var sb = new StringBuilder();
- for (var i = 0; i < hashed.Length; i++)
- {
- sb.Append(hashed[i].ToString("x2"));
- }
- return sb.ToString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment