【发布时间】:2014-02-06 19:28:35
【问题描述】:
我创建了一个博客,其中一些用户可以通过 Wordpress 仪表板上传图片。由于原始图像太大,该网站很快就陷入了困境。有些用户在上传图片之前不知道自己调整图片大小,我不想手动调整图片大小。
有什么方法可以设置上传图片的最大宽度和高度?我什至不希望原件留在网站上。我希望网站上最大的图片版本与我设置的宽度和高度限制相匹配。
【问题讨论】:
我创建了一个博客,其中一些用户可以通过 Wordpress 仪表板上传图片。由于原始图像太大,该网站很快就陷入了困境。有些用户在上传图片之前不知道自己调整图片大小,我不想手动调整图片大小。
有什么方法可以设置上传图片的最大宽度和高度?我什至不希望原件留在网站上。我希望网站上最大的图片版本与我设置的宽度和高度限制相匹配。
【问题讨论】:
在您的主题的functions.php中添加此代码,它将用调整大小的版本替换原始图像。
function replace_uploaded_image($image_data) {
// if there is no large image : return
if (!isset($image_data['sizes']['large'])) return $image_data;
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
$large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file'];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the large image
rename($large_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width'];
$image_data['height'] = $image_data['sizes']['large']['height'];
unset($image_data['sizes']['large']);
return $image_data;
}
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
文章来源:http://goo.gl/nkszUn
【讨论】:
那么你为什么不创建一个新的图像尺寸? http://codex.wordpress.org/Function_Reference/add_image_size
并在您的模板上使用该图像。
【讨论】:
add_image_size() 更复杂的解决方案,即使它没有在任何地方使用,它也会在服务器上保留完整尺寸的图像。他还要求上传/媒体库限制上传时的图像尺寸,这个“答案”都没有解决这两个问题。如果有的话,这真的应该是一个评论。
这将适用于新图片上传以及旧图片自动替换用户上传的大图片,并使用您在管理面板的media settings 中定义的大尺寸:
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
function replace_uploaded_image($image_data) {
// if there is no large image : return
if (!isset($image_data['sizes']['large'])) return $image_data;
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
// $large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file']; // ** This only works for new image uploads - fixed for older images below.
$current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],"/"));
$large_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['large']['file'];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the large image
rename($large_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width'];
$image_data['height'] = $image_data['sizes']['large']['height'];
unset($image_data['sizes']['large']);
return $image_data;
}
【讨论】: