如何从给定的电子邮件中构建GRAVATAR图像的URL

时间:2010-04-27 05:09:53

标签: php gravatar

使用 php 有一种简单的方法,一个简单的脚本或网址操作来构建与电子邮件对应的重力图像图片的网址?

Ex. http://gravatar.com/avatars/avatar.php?email=myemail@myserver.com这会返回一个jpeg或png图片。

如果没有类似示例的简单方法,您知道解决与电子邮件对应的gravatar网址的最简单方法是什么?感谢

6 个答案:

答案 0 :(得分:8)

您可以在其实施网站上找到包含PHP代码的示例脚本:http://en.gravatar.com/site/implement/php

答案 1 :(得分:8)

使用此:

$userMail = whatever_to_get_the_email;

$imageWidth = '150'; //The image size

$imgUrl = 'http://www.gravatar.com/avatar/'.md5($userMail).'fs='.$imageWidth;

答案 2 :(得分:4)

根脚本位于http://www.gravatar.com/avatar/ URL的下一部分是所请求用户的小写电子邮件地址的十六进制MD5 hash,其中所有空白都被修剪。您可以添加适当的文件扩展名,但它是可选的。

完整的API在这里http://en.gravatar.com/site/implement/

答案 3 :(得分:1)

虽然@ dipi-evil的解决方案工作正常,但我没有用它获得更大的图像。以下是我如何使其正常工作。

$userMail = 'johndoe@example';

$imageWidth = '600'; //The image size

$imgUrl = 'https://secure.gravatar.com/avatar/'.md5($userMail).'?size='.$imageWidth;

答案 4 :(得分:1)

您只能看到Gravatar的简单功能,可以:

  1. 检查电子邮件中是否包含图片。
  2. 返回该电子邮件的图像。

    <?php
    
    class GravatarHelper
    {
    
      /**
      * validate_gravatar
      *
      * Check if the email has any gravatar image or not
      *
      * @param  string $email Email of the User
      * @return boolean true, if there is an image. false otherwise
      */
      public static function validate_gravatar($email) {
        $hash = md5($email);
        $uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404';
        $headers = @get_headers($uri);
        if (!preg_match("|200|", $headers[0])) {
          $has_valid_avatar = FALSE;
        } else {
          $has_valid_avatar = TRUE;
        }
        return $has_valid_avatar;
      }
    
      /**
      * gravatar_image
      *
      *  Get the Gravatar Image From An Email address
      *
      * @param  string $email User Email
      * @param  integer $size  size of image
      * @param  string $d     type of image if not gravatar image
      * @return string        gravatar image URL
      */
      public static function gravatar_image($email, $size=0, $d="") {
        $hash = md5($email);
        $image_url = 'http://www.gravatar.com/avatar/' . $hash. '?s='.$size.'&d='.$d;
        return $image_url;
      }
    
    }
    

您可以使用以下代码:

if (GravatarHelper::validate_gravatar($email)) {
   echo GravatarHelper::gravatar_image($email, 200, "identicon");
}

答案 5 :(得分:0)

您可以使用此代码在Gravatar.com上获取电子邮件的头像,或者如果找不到该电子邮件的头像,则生成默认头像。

您只需要传递电子邮件作为参数,然后在项目中的任何地方调用此函数即可。

public function  get_avatar($email){

    $url = 'https://www.gravatar.com/avatar/'; // The gravatar's API url
    $url .= md5( strtolower( trim( $email ) ) ); // Hash the user's email
    $url .='.png?s=300'; // Get a custom image size

        //Extract the image if is set on Gravatar

    if ( isset($img) ) {
        foreach ( isset($atts) as $key => $val )
            $url .= ' ' . $key . '="' . $val . '"';
    }

    return $url; // Return the avatar's url or the default avatar if no image found.

}
相关问题