我正在遵循这里给出的示例(我修改了它只模糊,没有水印),在WordPress上传时制作一个模糊图像。问题是,如果上传的文件与设定的尺寸完全相同或更小,则WordPress将不会生成图像,因此也不会生成任何模糊的图像。
我尝试使用isset($meta['sizes']['background-image-blurred']['file'])
来确定是否已生成图像,如果没有,则copy()
源文件,但是这样就不会为图像生成任何WordPress“元数据”(对于非WordPress人员,元数据与您想象的不同),所以在使用wp_get_attachment_image
显示时,它将产生高度/宽度未定义的问题。
因此,我确信使用如下所示的wp_get_attachment_image
挂钩可能是错误的方法。它可能需要在图像上传过程中较早发生。
有什么好的方法可以让它正常工作吗?
/**
* Several functions relatting to blurring images on uploaded.
* @see https://codeable.io/community/how-to-watermark-wordpress-images-with-imagemagick/
*/
add_image_size( 'background-image-blurred', 1920, 1080, true );
function generate_blurred_image( $meta ) {
$time = substr( $meta['file'], 0, 7); // Extract the date in form "2015/04"
$upload_dir = wp_upload_dir( $time ); // Get the "proper" upload dir
$filename = $meta['sizes']['background-image-blurred']['file'];
$meta['sizes']['background-image-blurred']['file'] = blur_image( $filename, $upload_dir );
return $meta;
}
add_filter( 'wp_generate_attachment_metadata', 'generate_blurred_image' );
function blur_image( $filename, $upload_dir ) {
$original_image_path = trailingslashit( $upload_dir['path'] ) . $filename;
$image_resource = new Imagick( $original_image_path );
$image_resource->gaussianBlurImage( 10, 100 ); // See: http://phpimagick.com/Imagick/gaussianBlurImage
return save_blurred_image( $image_resource, $original_image_path );
}
function save_blurred_image( $image_resource, $original_image_path ) {
$image_data = pathinfo( $original_image_path );
$new_filename = $image_data['filename'] . '-blurred.' . $image_data['extension'];
// Build path to new blurred image
$blurred_image_path = str_replace($image_data['basename'], $new_filename, $original_image_path);
if ( ! $image_resource->writeImage( $blurred_image_path ) ) {
return $image_data['basename'];
}
// Delete the placeholder image WordPress made now that it's been blurred
unlink( $original_image_path );
return $new_filename;
}
wp_generate_attachment_metadata
(如果大小太小或相同,则不会生成任何新内容)。 - Drew Baker