为了压缩上传的图像,我编写了一个简单的代码片段,可以立即用一个可以指定质量的图像覆盖新上传的文件:
function wt_handle_upload_callback( $data ) {
$image_quality = 30; // Change this according to your needs
$file_path = $data[\'file\'];
$image = false;
switch ( $data[\'type\'] ) {
case \'image/jpeg\': {
$image = imagecreatefromjpeg( $file_path );
imagejpeg( $image, $file_path, $image_quality );
break;
}
case \'image/png\': {
$image = imagecreatefrompng( $file_path );
imagepng( $image, $file_path, $image_quality );
break;
}
case \'image/gif\': {
// Nothing to do here since imagegif doesn\'t have an \'image quality\' option
break;
}
}
return $data;
}
add_filter( \'wp_handle_upload\', \'wt_handle_upload_callback\' );
关于其他图像大小(只需更改返回值):
add_filter( \'wp_editor_set_quality\', function( $quality ) { return 30; } );