0

I have written a module with form api which can upload image with dynamic file name. I want to upload that file with auto compression. I cannot understand how will I achieve this. How can I implement this in submit callback. Below my code:

function MYMODULE_registration_form() {

  $form['name'] = [
    '#title'      => t('Name'),
    '#type'       => 'textfield',
    '#required'   => TRUE,
    '#size'       => 40,
    '#attributes' => ['placeholder' => t('Enter your name'),],
  ];

  $form['personal_info']['upload_pic'] = [
    '#title'       => t('Upload Photo'),
    '#type'        => 'file',
    '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif, bmp'),
  ];

  $form['submit'] = [
    '#value' => t('Submit'),
    '#type'  => 'submit',
  ];

  $form['#attributes']['enctype'] = 'multipart/form-data';

  return $form;
}

function MYMODULE_registration_form_submit($form, $form_state) {

  $name = $form_state['values']['name'];
  $count = 1;
  $original_username = $name;
  while (user_load_by_name($name)) {
    $name = $original_username . $count++;
  }

  $validators = [
    'file_validate_extensions' => ['png gif jpg jpeg bmp'],
  ];

  $uploadCheck = file_save_upload('upload_pic', $validators);

  if ($uploadCheck) {
    $parts = pathinfo($uploadCheck->filename);
    $imagename = str_replace(' ', '_', $original_username . '_' . $count . '.' . $parts['extension']);
    $target = "public://attorneys/" . $imagename;
    file_move($uploadCheck, $target, FILE_EXISTS_REPLACE);
    $picture_fid = $uploadCheck->fid;
  }
}
  • 1
    What do you mean by "auto compression"? Do you mean the image should be optimised? If so that's not how Drupal works. You upload an original, and use Image Styles to provide derivatives of it at different sizes/compression ratios – Clive Oct 29 '18 at 11:17
  • You probably have to build something custom for that. And that makes your question too broad. – leymannx Oct 29 '18 at 11:20
  • @Clive Yes. The image should be optimised before uploading or moving into public folder. Can it be possible? – Souvik Das Oct 29 '18 at 11:24
  • @leymannx Can you pls give me an idea how will I do it? – Souvik Das Oct 29 '18 at 11:25
-1

After a lot of R&D I have come to this conclusion and it is working fine:

Implement gulp package and install image optimisation plugin. Take ref from this url : https://www.tutorialspoint.com/gulp/gulp_optimizing_images.htm

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.