Convert User’s Avatar/Gravatar to a jpg or png on the Fly

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 ) ) );