Programmatically uploading and validating a user_picture I use the following code to modify the image in the user_picture field of user with uid 42:
// Get user.
$user = \Drupal\user\Entity\User::load(42);

// Create file.
$file = file_save_data(
  file_get_contents('/tmp/image.jpg'),
  'public://pictures/image.jpg'
);

// Set file.
$user-&gt;set('user_picture', $file-&gt;id());

// Save user.
$user-&gt;save();

It works great, but it's very simplistic and doesn't do any of what has been configured in /admin/config/people/accounts/fields/user.user.user_picture, e.g:

Validate &quot;Allowed file extensions&quot;.
Possibly downscale based on &quot;Maximum image resolution&quot;.
Save image in the &quot;File directory&quot; location.
Validate &quot;Maximum upload size&quot;.

Is there a way to somehow upload and set the file through what has been configured in the field?
You can access the values of the image field settings with:
$user-&gt;getFieldDefinition('user_picture')-&gt;getSettings();

Which will return an array, example:


You then can use file_save_upload
and you can pass to it for second param, an array containing all the validation functions

array $validators: (optional) An associative array of callback
functions used to validate the file. The keys are function names and
the values arrays of callback parameters which will be passed in after
the file entity. The functions should return an array of error
messages; an empty array indicates that the file passed validation.
The callback functions will be called in the order specified in the
array, then the hook hook_file_validate() will be invoked so other
modules can validate the new file.
 source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_validate/8.9.x 

Here are the validation functions you can use:


Source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/8.9.x