Is there a way to convert a user's gravatar/avatar to jpg on the fly? I have the following in my function:

get_avatar( $uid, 180 );

which returns the user's avatar image if I call it with straight PHP (i.e.: <?php echo get_avatar( $uid, 180 ); ?> but I want to convert the resulting file to a jpeg/png image so I can insert it into an FPDF function


1 Answer 1


The get_avatar function returns the Gravatar wrapped in <img> tags. In your case you'll want to use get_avatar_url to get just the URL of the image you need.

Combine that with WordPress' wp_remote_get and you can grab the image data into a variable or save it as an image.

$user            = wp_get_current_user();
$gravatar_url    = get_avatar_url( $user->ID, ['size' => '50'] );
$gravatar_source = wp_remote_get( $gravatar_url );

if ( ! is_wp_error( $gravatar_source ) && 200 == $gravatar_source['response']['code'] ) {
    $filename      = sanitize_file_name( $user->ID . '.jpg' );
    $gravatar_file = fopen( 'tmp /' . $filename, 'w' );
    fwrite( $gravatar_file, $gravatar_source['body'] );
    fclose( $gravatar_file );

This example is copied from this script which is otherwise largely unrelated.

Edit: If you just want to grab the URL into a PHP variable you can do this:

$current_user = wp_get_current_user();
$userdata     = get_userdata( $current_user->ID );

$gravatar_url = 'https://www.gravatar.com/avatar/' . md5( strtolower( trim( $userdata->user_email ) ) );
  • Thank you. get_avatar_url() would be fine - the resulting file doesn't actually need to be converted to a jpeg. This currently returns a png file (toogeemartialarts.com/wp-content/uploads/ultimatemember/<uid here>/profile_photo-190x190.png?1589039606). What is the number at the end of the file name? If I can just remove that, then everything is fine as is. Alternatively, I can use the script you provided but I am not sure how to find the path to the file? Commented May 9, 2020 at 5:56
  • "This currently returns a png file". What PHP code?
    – Brooke.
    Commented May 9, 2020 at 5:59
  • 1
    Sorry, accidentally pressed enter before I was finished. This gives me the path to the PNG file: <?php echo get_avatar_url( $uid ); ?> Commented May 9, 2020 at 6:02
  • 1
    The part at the end is the Epoch time. It's added there for cache busting. You can remove it, maybe with a bit of regex?
    – Brooke.
    Commented May 9, 2020 at 6:17
  • Or generate the URL yourself with just PHP en.gravatar.com/site/implement/images
    – Brooke.
    Commented May 9, 2020 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.