Created
January 3, 2018 10:24
-
-
Save fians/80405a143434fb4cb9379e95e4f6f0ee to your computer and use it in GitHub Desktop.
Optimize Image in PHP using Imagick according Google Pagespeed Recommendation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
HI I would like to know how to use your script in a automated way to process my images.
Thanks
Wonderful code. This helped me a lot. Thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please tell us how to use it? I am already installed and activated "imagick" and I need to compress all images in a specific folder. hank you