Resizing and cropping WordPress Images on the fly

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:
[php]require_once(‘your_path/aq_resizer.php’)[/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 ?>” />
[/php]

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

Get Aqua Resizer on GitHub

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}”;

//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);
}
}

}
[/php]

Leave a reply

0
Connecting
Please wait...
Send a message

Sorry, we aren't online at the moment. Leave a message.

Your name
* Email
* Describe your issue
Chat now

Need more help? Save time by starting your support request online.

Your name
* Email
* Describe your issue
We're online! Ask us anything!
Feedback

Help us help you better! Feel free to leave us any additional feedback.

How do you rate our support?