I am optimizing a site with large (dozens) quantity of images on page in a grid. For retina support the images are also need to be 2x sized.
The low hanging fruit was to make sure the thumbnail sizes are loaded (which are still considerable 520px wide because of the retina) instead of full original size they were.
However almost all of images are saved in PNG. Which is a huge waste on photographic imagery. It would make sense for generated thumbnails to be JPG… Except that there doesn’t seem to be a way to do it.
From looking through the core code the closest seems to be WP_Image_Editor->get_output_format()
but it’s doesn’t seem friendly to be easily adjusted and targeting specific sizes.
Are there any other points in code where I could try to change the type of image being generated?
You can use the wp_generate_attachment_metadata
filter:
function wpse_183835_to_jpeg( $meta, $post_id ) {
$sizes_to_convert = array(
'thumbnail',
);
$path = dirname( get_attached_file( $post_id ) );
foreach ( $sizes_to_convert as $size ) {
if ( ! empty( $meta['sizes'][ $size ] ) ) {
$data = $meta['sizes'][ $size ];
if ( $data['mime-type'] === 'image/png' && is_file( $file = "$path/{$data['file']}" ) ) {
if ( $image =@ imagecreatefrompng( $file ) ) {
// Change file extension
$file_jpg = preg_replace( '/\.[^\.]+$/', '', $data['file'] ) . '.jpg';
if ( @ imagejpeg( $image, "$path/$file_jpg", 90 ) ) { // Save new jpg version
// Update metadata with new filename
$meta['sizes'][ $size ]['file'] = $file_jpg;
// Delete png version
@ unlink( $file );
}
@ imagedestroy( $image );
}
}
}
}
return $meta;
}
add_filter( 'wp_generate_attachment_metadata', 'wpse_183835_to_jpeg', 10, 2 );
https://codex.wordpress.org/Function_Reference/wp_generate_attachment_metadata