8 – 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 = DrupaluserEntityUser::load(42);

// Create file.
$file = file_save_data(

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

// Save user.

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 “Allowed file extensions”.
  • Possibly downscale based on “Maximum image resolution”.
  • Save image in the “File directory” location.
  • Validate “Maximum upload size”.

Is there a way to somehow upload and set the file through what has been configured in the field?