Skip to content

Instantly share code, notes, and snippets.

@grim-reapper
Forked from fians/optimize.php
Created November 17, 2022 10:56
Show Gist options
  • Save grim-reapper/21ce0298a3d7d151da01ca827cada061 to your computer and use it in GitHub Desktop.
Save grim-reapper/21ce0298a3d7d151da01ca827cada061 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