0

I'm using the FAPI to provide the user an upload field for an image. The field is:

$form['product_img'] = [
  '#type' => 'managed_file',
  '#description' => 'Upload a PNG or JPG image of the product.',
  '#multiple' => FALSE,
  '#required' => TRUE,
  '#upload_location' => 'public://',
  '#upload_validators' => [
    'file_validate_is_img' => [],
    'file_validate_extensions' => ['png jpg jpeg']
  ]
];

A lot of the users are uploading images taken with their mobile device, resulting in the image in landscape.

The solutions I've seen involve the default file upload widget, but I need something that will automatically rotate the image after the upload.

1
1

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' => 'managed_file',
  '#description' => 'Upload a PNG or JPG image of the product.',
  '#multiple' => FALSE,
  '#required' => TRUE,
  '#upload_location' => 'public://',
  '#upload_validators' => [
    'file_validate_is_img' => [],
    'file_validate_extensions' => ['png jpg jpeg']
  ],
  '#process' => array('custom_managed_file_element_process'),
];


// Process callback

function custom_managed_file_element_process($element, &$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->uri);
      $variables = [
        'alt' => $file->filename,
        'path' => $file->uri,
        'style_name' => 'thumbnail', // change your style name here 
        'attributes' => [
          'class' => ['upload-preview'],
        ],
      ];

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

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

  return $element;

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.