我不确定我是否理解了这个问题。
这里有一个关于如何在上传时调整图像大小的解决方案,这样用户就无法上传大于1920x1920的图像。通过这种方式,您可以指示用户始终上载最大的图像,网站将为您完成其余操作以节省磁盘空间。
// Hook the function to the upload handler
// https://developer.wordpress.org/reference/hooks/wp_handle_upload/
add_filter(\'wp_handle_upload\', \'resize_image_after_upload\');
function resize_image_after_upload($image_data){
// Set to null to disable that width/height resizing
$max_width = 1920;
$max_height = 1920;
// Check if there is a valid file
if(empty($image_data[\'file\']) || empty($image_data[\'type\'])) {
return $image_data;
}
// NOTE: We are not resizing any gifs, to avoid resizing animated gifs
// (which I think is the most common gif nowadays)
$valid_types = array(\'image/png\',\'image/jpeg\',\'image/jpg\', \'image/webp\');
if(!in_array($image_data[\'type\'], $valid_types)) {
return $image_data;
}
// Get image image_editor
// https://developer.wordpress.org/reference/classes/wp_image_editor/
$image_editor = wp_get_image_editor($image_data[\'file\']);
if(is_wp_error($image_editor)) {
return $image_data;
}
// Check if the image editor supports the image type
if(!$image_editor->supports_mime_type($image_data[\'type\'])) {
return $image_data;
}
// Perform resizing
$sizes = $image_editor->get_size();
if((isset($sizes[\'width\']) && $sizes[\'width\'] > $max_width)
|| (isset($sizes[\'height\']) && $sizes[\'height\'] > $max_height)) {
// Resize, but do not crop
$image_editor->resize($max_width, $max_height, false);
// We will use the default recommended image quality
// Change, if you want to set a custom quality
//$image_editor->set_quality(90);
$image_editor->save($image_data[\'file\']);
}
return $image_data;
}
希望这有帮助!如果我更新此代码段,您也可以找到它
on my blog. 还有一个
plugin 对此,我个人更喜欢一个小片段。