WordPress add_image_size cropping problem: How to enable GD library

While trying to enable the image resizing option in WordPress I figured that the cropping feature of the function below (located in /wp-includes/media.php) did not work on my localhost.

function add_image_size( $name, $width = 0, $height = 0, $crop = false )

Using the code below in functions.php I was able to resize images (really badly though) but unable to crop them.

//This feature enables post-thumbnail support for a Theme
add_theme_support( 'post-thumbnails' );
add_image_size( 'post-image',  708, 400, true );
add_image_size( 'post-image-large',  708, 200, true );
add_image_size( 'post-image-small',  330, 150, true );

After some research I found a solution. In order to solve the cropping problem you will need to install the GD Library. GD is an open source code library for the dynamic creation of images. It supports JPG, PNG and XPM formats. Here is how to install it:

For Windows

All you need to do is to uncomment (remove the semi-colon at the beginning of the line) the line below on your php.ini

;extension=php_gd2.dll

Once it is done save it and do not forget to restart your Apache server.

For Linux

At first I tried to follow the Windows step but I got this error message:

Warning: PHP Startup: Unable to load dynamic library
'/opt/lampp/lib/php/extensions/no-debug-non-zts-20090626/php_gd2.dll'
 - /opt/lampp/lib/php/extensions/no-debug-non-zts-20090626/php_gd2.dll:
 cannot open shared object file: No such file or directory in Unknown on line 0

For Linux it is a little bit more complicated than only uncomment a line. To get it work you will have to install the library with the line below.

apt-get install php5-gd

Then restart Apache and it should work fine.

/etc/init.d/apache2 restart

or if you are using LAMPP/XAMPP

/opt/lampp/lampp restart

Once you have done all of this cropping should work for newly uploaded images. Unfortunetly you will need to re-process old pictures. To do so a great solution is to use the Regenerate Thumbnails plugins for WordPress.

Sources: