0

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).

2 Answers 2

0

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->filemime) && (strpos('image', $file->filemime) >= 0)) {
    $compressed = _[MODULE_NAME]_compress_image($file->uri, $file->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.

0

Give reSmush.it image style optimizer a try. It allows you to set which image styles should be optimized. It uses the excellent and free https://www.resmush.it/ API.

reSmush.it module works perfectly with s3fs (we are using it on all projects as well).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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