Upload an image to filesystem, rename it and set it as Profile Picture for current user I have the external link of an image where I am trying to:


Upload the image to filesystem.
Rename the image.
Set the owner of the image to current user.
Set the image as Profile Picture for current user.


So far I have:

$full_name = "John Smith";
$picture_url = "https://scontent.fbey14-1.fna.fbcdn.net/v/t31.0-8/14054356_124897527960923_50194821455451882_o.jpg?_nc_cat=106&amp;_nc_sid=09cbfe&amp;_nc_ohc=P4i5oscJf0IAX_KFCfR&amp;_nc_ht=scontent.fbey14-1.fna&amp;oh=c13b6b2d8712db359f3be5e1ec835340&amp;oe=5EF2B1A4";

// Download the picture to local filesystem.
$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);

// Get the Profile Pic ID.
$profile_pic_id = $profile_pic-&gt;id();

// Load the image.
$picture = \Drupal\file\Entity\File::load($profile_pic_id);

// Rename the image.
$picture-&gt;setFilename("$full_name.jpg");
// Set the owner of the profile picture file.
$picture-&gt;setOwner($current_user);

// Save the image.
$picture-&gt;save();

$current_user-&gt;set('user_picture', $profile_pic_id);
$current_user-&gt;save();


The image is indeed uploaded to filesystem under public://profile-pictures, also is successfully set as profile picture of the current user.

and the filename of the image at /user/*/edit edit page is set to: john-smith.jpg, however, the filename of the image at public://profile-pictures is 14054356_124897527960923_50194821455451882_o.jpg while I am expecting it to be john-smith.png !

How to rename the image at the filesystem ?

and does $picture-&gt;setOwner($current_user) will set the owner of the image to the current user ?
I agree with @Clive you can do it that why, and also you can download the image directly with the full_name.
To do so just change the line:

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);


by 

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures/$full_name.jpg", TRUE, FILE_EXISTS_REPLACE);


and remove the line:

$picture-&gt;setFilename("$full_name.jpg");