How can I auto-rotate an image on file upload in a custom form?
you can try the next code. You will have to create a new image style which rotates the image and then use it in prerendering on image preview.
$form['product_img'] = [
  '#type' =&gt; 'managed_file',
  '#description' =&gt; 'Upload a PNG or JPG image of the product.',
  '#multiple' =&gt; FALSE,
  '#required' =&gt; TRUE,
  '#upload_location' =&gt; 'public://',
  '#upload_validators' =&gt; [
    'file_validate_is_img' =&gt; [],
    'file_validate_extensions' =&gt; ['png jpg jpeg']
  ],
  '#process' =&gt; array('custom_managed_file_element_process'),
];


// Process callback

function custom_managed_file_element_process($element, &amp;$form_state, $form) {

  $element = file_managed_file_process($element, $form_state, $form);
  
  $element['#pre_render'][] = 'custom_managed_file_element_preview';
  
  return $element;
}


function custom_managed_file_element_preview(array $element) {

  if (empty($element['#file'])) {
    hide($element['remove_button']);
  }
  else {

    $file = $element['#file'];
    hide($element['upload']);
    hide($element['upload_button']);

      $info = image_get_info($file-&gt;uri);
      $variables = [
        'alt' =&gt; $file-&gt;filename,
        'path' =&gt; $file-&gt;uri,
        'style_name' =&gt; 'thumbnail', // change your style name here 
        'attributes' =&gt; [
          'class' =&gt; ['upload-preview'],
        ],
      ];

      if (is_array($info)) {
        $variables += $info;
      }

      $element['preview'] = [
        '#type' =&gt; 'markup',
        '#weight' =&gt; -150,
        '#markup' =&gt; theme('image_style', $variables)
      ];
    
  }

  return $element;

}