image optimize Issue I have installed S3 File System module, and all image files are served from AWS S3 bucket. The images served from S3 are not compressed. How to compress those images?

Following is the message I get when checking with page speed:


  Compressing
  https://example.s3-us-west-2.amazonaws.com/s3fs-public/test.jpg could
  save 22.4KiB (26% reduction).
When uploading images into Drupal, those are uploaded as it is and not compressed. To compress them you can check Image Optimize (or ImageAPI Optimize) Module.

Another solution is to add custom code in your custom module, which will compress image before a record is inserted into file_managed table, check code below:

/**
 * Implements hook_file_presave().
 */
function [MODULE_NAME]_file_presave($file) {
  if (!empty($file-&gt;filemime) &amp;&amp; (strpos('image', $file-&gt;filemime) &gt;= 0)) {
    $compressed = _[MODULE_NAME]_compress_image($file-&gt;uri, $file-&gt;uri, 75);
  }
}

/**
 * Helper function to compress images while uploading.
 *
 * @param string $source_url
 *   Source image URL.
 *
 * @param string $destination_url
 *   Destination image URL.
 *
 * @param string $quality
 *   Percentage of Image quality to compress.
 */
function _[MODULE_NAME]_compress_image($source_url, $destination_url, $quality) {
  $source_url = drupal_realpath($source_url);
  $destination_url = drupal_realpath($destination_url);

  $info = getimagesize($source_url);

  if ($info['mime'] == 'image/jpeg') {
    $image = imagecreatefromjpeg($source_url);
  }
  elseif ($info['mime'] == 'image/gif') {
    $image = imagecreatefromgif($source_url);
  }
  elseif ($info['mime'] == 'image/png') {
    $image = imagecreatefrompng($source_url);
  }
  else {
    return FALSE;
  }

  //save file
  imagejpeg($image, $destination_url, $quality);

  //return destination file
  return $destination_url;
}


NOTE: Change [MODULE_NAME] with your module name.