Skip to content

Instantly share code, notes, and snippets.

@cetver
Forked from fians/optimize.php
Created April 29, 2020 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cetver/a065c3790456f9710fc318f41c118b5d to your computer and use it in GitHub Desktop.
Save cetver/a065c3790456f9710fc318f41c118b5d to your computer and use it in GitHub Desktop.
Optimize Image in PHP using Imagick according Google Pagespeed Recommendation
/**
* Optimize image image
*
* https://developers.google.com/speed/docs/insights/OptimizeImages
* -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB
*
* @access public
* @param string $filePath Path of the file
* @return string Raw image result from the process
*/
public static function optimize($filePath)
{
/**
* Compress image
*/
$imagick = new Imagick();
$rawImage = file_get_contents($filePath);
$imagick->readImageBlob($rawImage);
$imagick->stripImage();
// Define image
$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight();
// Compress image
$imagick->setImageCompressionQuality(85);
$image_types = getimagesize($filePath);
// Get thumbnail image
$imagick->thumbnailImage($width, $height);
// Set image as based its own type
if ($image_types[2] === IMAGETYPE_JPEG)
{
$imagick->setImageFormat('jpeg');
$imagick->setSamplingFactors(array('2x2', '1x1', '1x1'));
$profiles = $imagick->getImageProfiles("icc", true);
$imagick->stripImage();
if(!empty($profiles)) {
$imagick->profileImage('icc', $profiles['icc']);
}
$imagick->setInterlaceScheme(Imagick::INTERLACE_JPEG);
$imagick->setColorspace(Imagick::COLORSPACE_SRGB);
}
else if ($image_types[2] === IMAGETYPE_PNG)
{
$imagick->setImageFormat('png');
}
else if ($image_types[2] === IMAGETYPE_GIF)
{
$imagick->setImageFormat('gif');
}
// Get image raw data
$rawData = $imagick->getImageBlob();
// Destroy image from memory
$imagick->destroy();
return $rawData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment