此问题是在上提出的Set JPEG compression for specific custom image sizes 艾哈迈德·M回答得很好
我当然会对那个帖子发表评论,但我没有50分的声誉。。。
我使用的代码与Ahmed的回答中的代码几乎相同,但我仍然面临的问题是,如果我在主题中使用特定的缩略图大小。例如,我在frontpage中有一个由较小方框组成的网格,它们有260px宽的图像。如果上传的图像最初小于Ahmed函数调整图像大小的值,那么它当然不会调整大小(也不应该),但也不会压缩图像。
Example:
如果我上传一张1200x800的图像并在头版中使用,它会被调整到更小的尺寸(520px宽,对于视网膜显示器来说是260px*2),质量也会被压缩。美好的但如果我上传的图像已经是500px宽(小于520px),它不会被调整大小,但也不会被压缩。很快,我的客户网站上就有很多大文件大小的图像,加载速度很慢。我应该如何更改此函数以始终将图像压缩到我希望缩略图的任何质量,而不考虑其原始尺寸?
代码:
//featured-image support
add_theme_support( \'post-thumbnails\' );
add_image_size( \'newsbox-thumb\', 520, 9999 ); // masonry news box-images =260px (520 retina) and unlimited height
add_image_size( \'fprelease-thumb\', 112, 9999 ); // fprelese feed logo, 56px (112px retina)
// https://wordpress.stackexchange.com/questions/74103/set-jpeg-compression-for-specific-custom-image-sizes
// set the quality to maximum
add_filter(\'jpeg_quality\', create_function(\'$quality\', \'return 100;\'));
add_action(\'added_post_meta\', \'ad_update_jpeg_quality\', 10, 4);
function ad_update_jpeg_quality($meta_id, $attach_id, $meta_key, $attach_meta) {
if ($meta_key == \'_wp_attachment_metadata\') {
$post = get_post($attach_id);
if ($post->post_mime_type == \'image/jpeg\' && is_array($attach_meta[\'sizes\'])) {
$pathinfo = pathinfo($attach_meta[\'file\']);
$uploads = wp_upload_dir();
$dir = $uploads[\'basedir\'] . \'/\' . $pathinfo[\'dirname\'];
foreach ($attach_meta[\'sizes\'] as $size => $value) {
$image = $dir . \'/\' . $value[\'file\'];
$resource = imagecreatefromjpeg($image);
if ($size == \'newsbox-thumb\') {
// set the jpeg quality for \'newsbox-thumb\' size
imagejpeg($resource, $image, 60);
} elseif ($size == \'fprelease-thumb\') {
// set the jpeg quality for the \'fprelease-thumb\' size
imagejpeg($resource, $image, 85);
} else {
// set the jpeg quality for the rest of sizes
imagejpeg($resource, $image, 80);
}
// or you can skip a paticular image size
// and set the quality for the rest:
// if ($size == \'splash\') continue;
imagedestroy($resource);
}
}
}
}