October 22

Resizing and cropping WordPress Images on the fly


If you are a wordpress developer, and you are looking for a way to crop and resize images on the fly, we have found a little script on the internet, that can help you do it. It’s name is Aqua Resizer, and it is native, which means it uses wordpress built in functions to automatically process the images. Main reasons to use it:

  • It’s not a plugin, it’s just a simple file that can be pasted into functions.php, or included via require_once() function.
  • It is very simple, yet it gets the job done perfectly
  • It can also crop an already cropped image
  • It’s open source

How to add it to wordpress?

    • You can use this line of code in functions.php:

Here’s a sample usage of the script:

[php] <?php
$thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb,’full’); //get img URL
$image = aq_resize( $img_url, 560, 310, true ); //resize & crop img
<img src=”<?php echo $image ?>” />

To find out more useful informations, and to download the script, click on the link bellow.

[button color=green size=large url=”https://github.com/syamilmj/Aqua-Resizer” target=blank ]Get Aqua Resizer on GitHub[/button]

Additional code for retina display(optional):

AJ Clarke from WpExplorer has came up with a small code for generating retina display images (which is basically the doubled size of the image). Just add this code before return $image.

Here we go:

[php] $retina_w = $dst_w*2;
$retina_h = $dst_h*2;

//get image size after cropping
$dims_x2 = image_resize_dimensions($orig_w, $orig_h, $retina_w, $retina_h, $crop);
$dst_x2_w = $dims_x2[4];
$dst_x2_h = $dims_x2[5];

// If possible lets make the @2x image
if($dst_x2_h) {

//@2x image url
$destfilename = “{$upload_dir}{$dst_rel_path}-{$suffix}@2x.{$ext}”;

Books Worth Reading:

//check if retina image exists
if(file_exists($destfilename) && getimagesize($destfilename)) {
// already exists, do nothing
} else {
// doesnt exist, lets create it
$editor = wp_get_image_editor($img_path);
if ( ! is_wp_error( $editor ) ) {
$editor->resize( $retina_w, $retina_h, $crop );
$editor->set_quality( 100 );
$filename = $editor->generate_filename( $dst_w . ‘x’ . $dst_h . ‘@2x’ );
$editor = $editor->save($filename);



crop, image, resize, wordpress

You may also like

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Get in touch

0 of 350