我想在WordPress中生成额外的图像大小。 WP可让您像这样使用add_image_size
:
// Make sure featured images are enabled
add_theme_support( 'post-thumbnails' );
// Add featured image sizes
add_image_size( 'original-img', 2000, 99999 );
如果图像具有最小值。宽度为2000px,将生成图像尺寸。 但是,如果图像较小,则不会生成自定义尺寸。
是否可以选择每次为自定义图像大小创建图像,无论上传的图像大小如何?还是有可能另外保存原始图像?
解释为什么要实现以下目的:我需要在图像上添加水印,但也需要没有水印的原始图像(或非常大的图像)。
我也尝试过使用“大”图像,但是这里存在同样的问题。通过上传小于1024像素的图像,将不会创建图像尺寸。
答案 0 :(得分:1)
您可以挂钩wp_generate_attachment_metadata
并在那里复制上载的图像(如果尚未创建)。我在下面包含了执行此操作的代码。
将此添加到您的functions.php中。注释每个步骤以解释其作用,但基本上是在上传过程中进行的:
cat-700x520px.jpg
)original-img
然后,您可以在代码中使用original-img
自定义大小,并始终显示图片。
// Make sure featured images are enabled
add_theme_support( 'post-thumbnails' );
// Add featured image sizes
add_image_size( 'original-img', 2000, 99999 );
// Hook into the upload process
add_filter('wp_generate_attachment_metadata','copy_original_img');
// Check if the original image was added, if not make a copy and add it as original-img
function copy_original_img($image_data) {
// if the original-img was created, we don't need to do anything
if (isset($image_data['sizes']['original-img']))
return;
// 1. make a copy of the uploaded image to use for original-img
$upload_dir = wp_upload_dir();
$uploaded_img = $image_data['file'];
$img_w = $image_data['width'];
$img_h = $image_data['height'];
// construct the filename for the copy in the format: imagename-WxH.extn
$path_parts = pathinfo($uploaded_img);
$new_img = $path_parts['filename']."-".$img_w."x".$img_h.".".$path_parts['extension'];
// make a copy of the image
$img_to_copy = $upload_dir['path'] . '/'.$uploaded_img;
$new_img_path = $upload_dir['path'] . '/'.$new_img;
$success = copy($img_to_copy,$new_img_path);
// 2. If the image was copied successfully, add it into the image_data to be returned:
if ($success){
$image_data['sizes']['original-img']['file'] = $new_img;
$image_data['sizes']['original-img']['width'] = $img_w ; // same as uploaded width
$image_data['sizes']['original-img']['height'] = $img_h; // same as uploaded height
$image_data['sizes']['original-img']['mime-type'] = mime_content_type($new_img_path);
}
return $image_data;
}