这是我写的一篇文章,因为我的客户使用的是非常高质量的PNG,而他们在web上使用的JPG可能更具损耗性。注意,这仍然保留原始图像,仅更改缩略图。将此添加到您的函数中。php
<?php
//Force PNG Thumbnails into JPGs
add_filter(\'wp_generate_attachment_metadata\',\'force_png_to_jpg\');
function force_png_to_jpg($image_data) {
$sizes = array(\'thumbnail\',\'medium\',\'large\');
$upload_dir = wp_upload_dir();
$file = $upload_dir[\'path\'] . \'/\' . basename($image_data[\'file\']);
foreach($sizes as $size){
if(isset($image_data[\'sizes\'][$size]))
{
if( $image_data[\'sizes\'][$size][\'mime-type\'] == "image/png" ){
//change format and filename for jpg
$dest_file = preg_replace(\'/\\.png$/i\', \'.jpg\', $image_data[\'sizes\'][$size][\'file\']);
$image_data[\'sizes\'][$size][\'file\'] = $dest_file;
$image_data[\'sizes\'][$size][\'mime-type\'] = "image/jpg";
//process image into jpg using standard gd lib
$image = imagecreatefrompng($file);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
$bg = imagescale($bg, $image_data[\'sizes\'][$size][\'width\'], $image_data[\'sizes\'][$size][\'height\'] );
imagedestroy($image);
//set quality and save
$quality = 80; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $upload_dir[\'path\'] . \'/\' . $dest_file, $quality);
imagedestroy($bg);
}
}
}
return $image_data;
}