Become Wordpress Professional - Your Ultimate Wordpress Guide

Tuesday, 3 September 2013

How to Sharpen Resized Images in Wordpress

We have often witnessed that images become blurred after uploading them on wordpress either while writing a post, a page or uploading it directly into the media library in wordpress.

This tutorial will help your images get sharpened after uploading them into wordpress. We would insert a block of code that is a method which will automatically perform this function for us. Here is the difference before image sharpening and after image sharpening in wordpress:

As you can see that by default the images show up blurry and their detail is a bit rough as compared to the sharpened image where the details of the image is more prominent. So lets look how easy it is to force wordpress to sharpen the images that you upload.

First of all you need to open up your theme's function.php file. You can find it after logging into the wordpress admin panel and then navigate to Appearance > Editor. Click to open functions.php file

Copy the following code as it is and paste at the bottom of your functions.php file:
function ajx_sharpen_resized_files( $resized_file ) {

    $image = wp_load_image( $resized_file );
    if ( !is_resource( $image ) )
        return new WP_Error( 'error_loading_image', $image, $file );

    $size = @getimagesize( $resized_file );
    if ( !$size )
        return new WP_Error('invalid_image', __('Could not read image size'), $file);
    list($orig_w, $orig_h, $orig_type) = $size;

    switch ( $orig_type ) {
        case IMAGETYPE_JPEG:
            $matrix = array(
                array(-1, -1, -1),
                array(-1, 16, -1),
                array(-1, -1, -1),

            $divisor = array_sum(array_map('array_sum', $matrix));
            $offset = 0; 
            imageconvolution($image, $matrix, $divisor, $offset);
            imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
        case IMAGETYPE_PNG:
            return $resized_file;
        case IMAGETYPE_GIF:
            return $resized_file;

    return $resized_file;

add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files',900);
Basically What this function does is that it handles all the mathematical logical operations required to sharpen the image being uploaded. then we use a wordpress filter hook to tell wordpress when exactly do we want to run this function. In this case we are running this function right after it is uploaded either via post, page or media library.

Note: Please Note that image sharpening will only be applied on images with a format JPG/JPEG. It will not work on a png image.
Now that you have setup the automatic image sharpening, your images will be rendered in high quality on your site.

1 comment:

Please Avoid Spamming. Comments will be moderated before they are published.