生成Avatar

在诸如MSDN等论坛中,每个用户默认会根据名字生成唯一不同的头像图片(如果没有上传自己的头像的话)。这个功能是怎么实现的呢?

1)需要到某个网站(Avatar)请求获取一个随机图片。

2)格式:www.gravatar.com/avatar/HASH?r=PG&s=256&default=identicon

数值(可以是MD5)

3)HASH的生成(本文主要讨论这个,其余参数可以打开去自行查看参数说明):

   3.1)使用MD5CryptoServiceProvider的ComputeHash方法对已经转化成Byte数组的字符串加密。

   3.2)然后使用格式化把生成的Byte数组按照十六进制输出。

4)源代码如下:

Imports System.Net

Imports System.Security.Cryptography

Imports System.Text

Imports System.IO



Public Class Form1

    Private Async Function Generate(name As String) As Task(Of Stream)

        Dim s As Stream = Nothing



        Await Task.Factory.StartNew(Sub()

                                        Dim md5 As New MD5CryptoServiceProvider

                                        Dim bytes() As Byte = md5.ComputeHash(Encoding.UTF32.GetBytes(TextBox1.Text))

                                        Dim result As New StringBuilder



                                        For Each Str As String In bytes.Select(Function(b) b.ToString("x"))

                                            result.Append(Str)

                                        Next



                                        Dim req As WebRequest = WebRequest.Create("http://www.gravatar.com/avatar/" & result.ToString() & "?r=PG&s=256&default=identicon")



                                        Dim resp As WebResponse = req.GetResponse()

                                        s = resp.GetResponseStream()

                                    End Sub)

        Return s

    End Function

    Private Sub Form1_Click(sender As Object, e As EventArgs) Handles MyBase.Click



    End Sub



    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Text = "请稍后……"

        Dim s As Stream = Await Generate(TextBox1.Text)

        PictureBox1.Image = Image.FromStream(s)

        Text = "生成完毕"

    End Sub

End Class

结果测试:

 

生成Avatar

你可能感兴趣的:(tar)