我创建了一个博客,其中一些用户可以通过Wordpress信息中心上传图片。由于原始图像太大,网站很快陷入困境。有些用户在上传图片之前没有自己调整图片大小的知识,我不想手动调整图片大小。
有什么办法可以为上传的图片设置最大宽度和高度吗?我甚至不希望原件留在网站上。我希望网站上最大的图像版本与我设置的宽度和高度限制相匹配。
答案 0 :(得分:3)
在主题的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
答案 1 :(得分:0)
那么为什么不创建新的图像尺寸? http://codex.wordpress.org/Function_Reference/add_image_size
并在模板上使用该图片。
答案 2 :(得分:0)
这适用于新图片上传以及旧图片上传,用管理员面板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;
}