Skip to content

Instantly share code, notes, and snippets.

@paulnett
Created May 17, 2012 07:31
Show Gist options
  • Select an option

  • Save paulnett/2717194 to your computer and use it in GitHub Desktop.

Select an option

Save paulnett/2717194 to your computer and use it in GitHub Desktop.
Generate B + W images in WordPress
<?php
add_image_size('thumbnail-bw', 400, 0, false);
add_filter('wp_generate_attachment_metadata','bw_images_filter');
/**
* Takes an image and creates a black and white version of it
* Callback for add_filter('wp_generate_attachment_metadata','bw_images_filter');
* Hat Tip: http://bavotasan.com/2011/create-black-white-thumbnail-wordpress/
*
* @return array
* @author Keir Whitaker
**/
function bw_images_filter($meta) {
$file = wp_upload_dir();
$file = trailingslashit($file['path']).$meta['sizes']['thumbnail-bw']['file'];
list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
$image = wp_load_image($file);
imagefilter($image, IMG_FILTER_GRAYSCALE);
switch ($orig_type) {
case IMAGETYPE_GIF:
$file = str_replace(".gif", "-bw.gif", $file);
imagegif( $image, $file );
$meta['sizes']['thumbnail-bw']['file'] = str_replace(".gif", "-bw.gif", $meta['sizes']['thumbnail-bw']['file']);
break;
case IMAGETYPE_PNG:
$file = str_replace(".png", "-bw.png", $file);
imagepng( $image, $file );
$meta['sizes']['thumbnail-bw']['file'] = str_replace(".png", "-bw.png", $meta['sizes']['thumbnail-bw']['file']);
break;
case IMAGETYPE_JPEG:
$file = str_replace(".jpg", "-bw.jpg", $file);
imagejpeg( $image, $file );
$meta['sizes']['thumbnail-bw']['file'] = str_replace(".jpg", "-bw.jpg", $meta['sizes']['thumbnail-bw']['file']);
break;
}
return $meta;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment