Last active
March 31, 2025 17:24
-
-
Save wmelton/bbf82ce43103fae7efe5946734e4de19 to your computer and use it in GitHub Desktop.
Optimize Images on Upload for Wordpress
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
<?php | |
/** | |
* Wordpress function to optimize image in accordance with Google Pagespeed recommendations upon | |
* upload. Supports jpeg/jpg image types. | |
* | |
* Authored by: Wes Melton | |
* Source: https://gist.github.com/wmelton/bbf82ce43103fae7efe5946734e4de19 | |
* | |
* This function compresses the image, converts it to a progressive JPEG, and strips ICC information. | |
* It also converts it to sRGB colorspace, compresses to 85% quality and then saves it back. | |
* This ensures that photos uploaded to Wordpress are being uploaded at the correct optimization levels. Obviously | |
* the user needs to not upload a 4k image, as the compressed file size would still be enormous for mobiles. | |
* | |
* Original Google Recommendation: https://developers.google.com/speed/docs/insights/OptimizeImages | |
* | |
* ** I haven't battle tested this. Suggest fixes in the comments! | |
**/ | |
function _optimize_on_upload( $obj ) { | |
//Ensure the ImageMagick extension is installed. | |
if( extension_loaded('imagick') || class_exists("Imagick") ){ | |
if( 'image' != substr( $obj['type'], 0, 5 ) ) | |
{ | |
return $obj; | |
} | |
$imageURL = $obj['file']; | |
$pathParts = pathinfo($imageURL); | |
if(strtolower( $pathParts['extension'] ) != 'jpg' && strtolower( $pathParts['extension'] ) != 'jpeg') | |
{ | |
return $obj; | |
} | |
//New ImageMagick object. | |
$img = new Imagick(); | |
$img->readImage($obj['file']); | |
//Google PageSpeed requires progressive jpegs if jpeg. | |
$img->setInterlaceScheme(Imagick::INTERLACE_PLANE); | |
//Google requires compressions quality of 85. | |
$img->setImageCompressionQuality(85); | |
//Set colorspace to sRGB. | |
$img->setImageColorspace(13); | |
//Imagick library doesn't use the 4:2:0 pattern for chroma subsampling. | |
//This is a PHP specific method of acheiving the same output. | |
$img->setSamplingFactors(array('2x2', '1x1', '1x1')); | |
//Strip image of ICC profiles, etc. | |
$img->stripImage(); | |
//Save it back to the server. | |
$img->writeImage(); | |
} | |
return $obj; | |
} | |
add_filter( 'wp_handle_upload', '_optimize_on_upload' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment