Aqua Resizer Reloaded: Image Cropping for WordPress

WordPress allows you to create different sizes of images so that you can use them easily in your theme and make your blog/website visually exciting. By default, WordPress creates three sizes (thumbnail, medium and large) apart from the original. One can define other image sizes as well using the “add_image_size” function, which is very commonly used in theme. It has one drawback though.

All the resized copies of images are saved in your uploads folder among original images. There is no way to delete the images of different sizes by default. There are plugins (such as Regenerate Thumbnails) to regenerate thumbnails, but it works only for active image sizes. If you have been using some other theme earlier, chances are the images of theme-specific sizes will remain on your hosting space. The number of unnecessary images will keep increasing with every new theme, leading to clutter and unproductive use of hosting space. Ideally, WordPress should provide option to delete all images other than the originals at any point.

Until WordPress has a solution to the problem of clutter due to unused image sizes, you are better off using a custom image resizing code (TimThumb) for creating multiple sizes of images. In order to avoid straining your server, the images should be saved in a folder for reuse.

Aqua Resizer is a quick solution to the problem. It allows you to create different sizes of images by just one line of code. With Aqua Resizer, the only required inputs are the URL and width. You also have the additional options such as the height, crop, and array return.

Once you include the code or Aqua Resizer file, you can use it to create custom image sizes in your theme as such:

aq_resize($image_url,$width);

In the code above, $image_url will have to be replaced with URL value and $width with width of resized image to be generated. When all parameter are used, the code should look like as follows:

aq_resize( $url, $width, $height, $crop, $single );

In the code above, $height is the desired height of resized image, $crop can be true or false based on whether images have to be cropped to exact dimension or in the same width:height ratio and $single can be true (default value) or false based on the output required: URL link or array of URL link, width and height.

Parameters

$url

(str)(required) – The image URL you want to resize/crop. Note: Must be uploaded through WordPress. Default: none

$width

(integer)(optional) – The width to be resized into in pixels. If $width is not specified, $height is required. Default: null

$height

(integer)(optional) – The height to be resized into in pixels. If $height is not specified, $width is required. Default: null

$crop

(boolean)(optional) – Crop the image or not. False – Soft proportional crop mode ; True – Hard crop mode.. Default: false

$single

(boolean)(optional) False – Return an array containing url, width, and height. True – return url. Default: true

Return

Return image URL if single is set to true or not set. Otherwise return array() containing

  • [0] => url
  • [1] => width
  • [2] => height

I like Aqua Resizer very much, but the original code saved images in a cache folder where the script file was present. Not the best way of handling.

While working for a custom WordPress theme, I modified the code to save all resized images in a folder named as “cache” present in the “Uploads” directory of WordPress. (By default, all image and media are saved in the “Uploads” folder in the “wp-content” folder. You can set your own uploads folder.)

The modified Aqua Resized allows you to include it in your WordPress themes anywhere. You can create a new PHP file for the code and then include the file via functions.php file or anywhere else. The resized images are always saved in the “cache” folder in the “uploads” directory, making it more intuitive to find the cache folder. If you ever need to get rid of resized images, just delete the code referencing the unused file sizes or modify the  size in the code. Now, delete the “cache” folder to let new resized images, if any, be created and cached.

Here’s the code of the Aqua Resizer Reloaded. Copy the code in a separate PHP file and include it in your theme (in the functions.php file, maybe) or directly paste the code in the theme functions file or any relevant file. Enjoy!


<?php

/**
* Title        : Aqua Resizer
* Description    : Resizes WordPress images on the fly
* Version    : 1.1.6
* Author    : Syamil MJ
* Author URI    : http://aquagraphite.com
* License    : WTFPL - http://sam.zoy.org/wtfpl/
* Documentation    : https://github.com/sy4mil/Aqua-Resizer/
*
* @param    string $url - (required) must be uploaded using wp media uploader
* @param    int $width - (required)
* @param    int $height - (optional)
* @param    bool $crop - (optional) default to soft crop
* @param    bool $single - (optional) returns an array if false
* @uses        wp_upload_dir()
* @uses        image_resize_dimensions() | image_resize()
* @uses        wp_get_image_editor()
*
* @return str|array
*/


/**************

Modified to save all images in the 'cache' folder of your WordPress 'uploads' directory.
Author: Xtrapunch.com

**************/

function aq_resize( $url, $width, $height = null, $crop = null, $single = true ) {

//validate inputs
if(!$url OR !$width ) return false;

//define upload path & dir
$upload_info = wp_upload_dir();
$upload_dir = $upload_info['basedir'];
$upload_url = $upload_info['baseurl'];


$aqua_dir = $upload_info['basedir'].'/cache';
$aqua_url = $upload_info['baseurl'].'/cache';


//check if $img_url is local
if(strpos( $url, $upload_url ) === false) return false;

//define path of image
$rel_path = str_replace( $upload_url, '', $url);
$img_path = $upload_dir . $rel_path;

//check if img path exists, and is an image indeed
if( !file_exists($img_path) OR !getimagesize($img_path) ) return false;

//get image info
$info = pathinfo($img_path);
$ext = $info['extension'];
list($orig_w,$orig_h) = getimagesize($img_path);

//get image size after cropping
$dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop);
$dst_w = $dims[4];
$dst_h = $dims[5];

//use this to check if cropped image already exists, so we can return that instead
$suffix = "{$dst_w}x{$dst_h}";
$dst_rel_path = str_replace( '.'.$ext, '', $rel_path);
$destfilename = "{$aqua_dir}{$dst_rel_path}-{$suffix}.{$ext}";

if(!$dst_h) {
//can't resize, so return original url
$img_url = $url;
$dst_w = $orig_w;
$dst_h = $orig_h;
}
//else check if cache exists
elseif(file_exists($destfilename) && getimagesize($destfilename)) {
$img_url = "{$aqua_url}{$dst_rel_path}-{$suffix}.{$ext}";
}
//else, we resize the image and return the new resized image url
else {

// Note: This pre-3.5 fallback check will edited out in subsequent version
if(function_exists('wp_get_image_editor')) {

$editor = wp_get_image_editor($img_path);

if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
return false;

$resized_file = $editor->save($destfilename);

if(!is_wp_error($resized_file)) {
$resized_rel_path = str_replace( $aqua_dir, '', $resized_file['path']);
$img_url = $aqua_url . $resized_rel_path;
} else {
return false;
}

} else {

$resized_img_path = image_resize( $img_path, $width, $height, $crop ); // Fallback foo
if(!is_wp_error($resized_img_path)) {
$resized_rel_path = str_replace( $upload_dir, '', $resized_img_path);
$img_url = $upload_url . $resized_rel_path;
} else {
return false;
}

}

}

//return the output
if($single) {
//str return
$image = $img_url;
} else {
//array return
$image = array (
0 => $img_url,
1 => $dst_w,
2 => $dst_h
);
}

return $image;
}