So I'm following the example given here (which I modified to only blur, no watermark), to make a blurred image in WordPress on upload. The problem is, that if the uploaded file is the exact same size, or smaller, than the set size, then WordPress will not generate an image, and hence no blurred one will be made.
I tried using a isst($meta['sizes']['background-image-blurred']['file'])
to determine if one was made, and if not then copy()
the source file, but then no WordPress "metadata" would be generated for the image (for non-WordPress people, the metadata is different than what you think), so it would give height/width undefined problems when displaying using wp_get_attachment_image
.
So I'm convinced using wp_get_attachment_image
hook as shown below is probably the wrong way to do this. It probably needs to happen earlier in the image upload process.
Any ideas on how to best get this working?
/**
* 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
is only called if a new version is made (and if the size is too small or the same, nothing new is made). – Scantling