Last Updated: February 25, 2016
·
4.063K
· lightandsounds

Automatically convert uploaded images to grayscale in Wordpress

add_filter('wp_generate_attachment_metadata','rb_bw_filter');

function rb_bw_filter($meta) {

    $path = wp_upload_dir(); // get upload directory
    $file = $path['basedir'].'/'.$meta['file']; // Get full size image

    $files[] = $file; // Set up an array of image size urls

    foreach ($meta['sizes'] as $size) {
        $files[] = $path['path'].'/'.$size['file'];
    }

    foreach ($files as $file) { // iterate through each image size

        // Convert image to grayscale credit to http://ottopress.com/2011/customizing-wordpress-images/

        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:
                imagegif( $image, $file );
                break;
            case IMAGETYPE_PNG:
                imagepng( $image, $file );
                break;
            case IMAGETYPE_JPEG:
                imagejpeg( $image, $file );
                break;
        }
    }
    return $meta;
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside