Skip to content

Instantly share code, notes, and snippets.

@dboulet
Created February 5, 2015 19:10
Show Gist options
  • Save dboulet/497d676c60df6fc46f2d to your computer and use it in GitHub Desktop.
Save dboulet/497d676c60df6fc46f2d to your computer and use it in GitHub Desktop.
Convert images to grayscale in WordPress
<?php
/**
* Grayscale Image Editor
*
* Expands GD Image Editor class by adding a grayscale filter.
*/
require_once ABSPATH . 'wp-includes/class-wp-image-editor.php';
require_once ABSPATH . 'wp-includes/class-wp-image-editor-gd.php';
class Grayscale_Image_Editor extends WP_Image_Editor_GD {
/**
* Convert image to grayscale.
*
* @return boolean|WP_Error
*/
public function make_grayscale() {
// Create copy of image.
$w = $this->size['width'];
$h = $this->size['height'];
$dest = wp_imagecreatetruecolor( $w, $h );
imagecopy( $dest, $this->image, 0, 0, 0, 0, $w, $h );
if ( is_resource( $dest ) ) {
// Apply grayscale filter to copy.
if ( imagefilter( $dest, IMG_FILTER_GRAYSCALE ) && imagegammacorrect( $dest, 1.0, 1.1 ) ) {
// Make the image progressive as a performance enhancement.
imageinterlace( $dest, 1 );
imagedestroy( $this->image );
$this->image = $dest;
return TRUE;
}
}
return new WP_Error( 'image_grayscale_error', __( 'Image grayscale conversion failed.' ), $this->file );
}
}
<?php
/**
* Convert images to grayscale.
*/
function image_grayscale_filter( $metadata, $attachment_id ) {
require_once 'class-grayscale-image-editor.php';
$path = wp_upload_dir();
$basedir = trailingslashit( $path['basedir'] );
$subdir = trailingslashit( dirname( $metadata['file'] ) );
$image_sizes = get_intermediate_image_sizes();
// Gather a list of all generated image files.
$files = array();
foreach ( $image_sizes as $size_name ) {
if ( isset( $metadata['sizes'][$size_name]['file'] ) ) {
$files[] = $basedir . $subdir . $metadata['sizes'][$size_name]['file'];
}
}
// Reduce duplicates
$files = array_unique( $files );
// Make sure not to include the original file.
$files = array_diff( $files, array( $basedir . $metadata['file'] ) );
// Apply grayscale to each image.
foreach ( $files as $file ) {
$image = new Grayscale_Image_Editor( $file );
$image->load();
if ( $image->make_grayscale() ) {
$image->save( $file );
}
}
return $metadata;
}
add_filter( 'wp_generate_attachment_metadata', 'image_grayscale_filter', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment