phpdrupal-7form-api

Drupal form api file upload with auto compression


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'] = array(
    '#title'=> t('Name'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#size' => 40,
    '#attributes' => array('placeholder' => t('Enter your name'),),
  );

$form['personal_info']['upload_pic'] = array(
    '#title' => t('Upload Photo'),
    '#type' => 'file',
    '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif, bmp'),
  );
 $form['submit'] = array(
      '#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 = array(
      'file_validate_extensions' => array('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;
    }

}

Solution

  • 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