Skip to content

Instantly share code, notes, and snippets.

@fugudesign
Last active April 27, 2018 17:06
Show Gist options
  • Save fugudesign/a183764e4cf475f036a0dae55b866368 to your computer and use it in GitHub Desktop.
Save fugudesign/a183764e4cf475f036a0dae55b866368 to your computer and use it in GitHub Desktop.
Wordpress attachment images: generate a grayscale copy of main (full) image referenced as an image_size
/**
* Generate a grayscale copy of main (full) image referenced as an image_size
*/
function add_grayscale_image_size( $image_sizes ) {
$image_sizes[] = 'grayscale';
return $image_sizes;
}
add_filter( 'intermediate_image_sizes', 'add_grayscale_image_size' );
function grayscale_images_filter( $meta ) {
$file = wp_upload_dir();
$filepath = $file['path'];
$file = trailingslashit( $filepath ) . $meta['file'];
$newfile = preg_replace( '/(\.(png|gif|jpg|jpeg))/', '-grayscale$1', $file );
list( $orig_w, $orig_h, $orig_type ) = @getimagesize( $file );
$image = wp_load_image($file);
if ( is_resource( $image ) ) {
imagefilter($image, IMG_FILTER_GRAYSCALE);
}
switch ($orig_type) {
case IMAGETYPE_GIF: imagegif( $image, $newfile ); break;
case IMAGETYPE_PNG: imagepng( $image, $newfile ); break;
case IMAGETYPE_JPEG: imagejpeg( $image, $newfile ); break;
}
$grayscale = [
'file' => str_replace( trailingslashit( $filepath ), "", $newfile ),
'width' => $meta['width'],
'height' => $meta['height'],
];
$meta['sizes']['grayscale'] = $grayscale;
return $meta;
}
add_filter( 'wp_generate_attachment_metadata', 'grayscale_images_filter' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment