Skip to content

Instantly share code, notes, and snippets.

@edirpedro
Last active August 29, 2015 14:26
Show Gist options
  • Save edirpedro/da3d6be9bdc6ea28f4b5 to your computer and use it in GitHub Desktop.
Save edirpedro/da3d6be9bdc6ea28f4b5 to your computer and use it in GitHub Desktop.
Method "Exact" for WP Image Editor, will return the image with the exactly size requested, scaling it if necessary.
/*
* Method "exact" for WP Image Editor
*
* Usage: exact($image, array(200, 200, true)) using same "resize" arguments from WP Image Editor.
* https://codex.wordpress.org/Class_Reference/WP_Image_Editor
*
* @description: Return the exact size from an image, scaling it when necessary.
* @created: 31/07/15
* @param object $image - The WP Image Editor instance
* @param array $args - The same arguments from "resize" method
*/
function exact($image, $args) {
$orig_size = $image->get_size();
$orig_w = $orig_size['width'];
$orig_h = $orig_size['height'];
$dest_w = $args[0];
$dest_h = $args[1];
$ratio = 1;
if($orig_w < $dest_w)
$ratio = $dest_w / $orig_w;
if($orig_h < $dest_h) {
$ratio_h = $dest_h / $orig_h;
if($ratio_h > $ratio)
$ratio = $ratio_h;
}
if($ratio > 1) {
$new_w = ceil($orig_w * $ratio);
$new_h = ceil($orig_h * $ratio);
$image->crop(0, 0, $orig_w, $orig_h, $new_w, $new_h);
}
call_user_func_array(array($image, 'resize'), $args);
}
// Testing
$image = wp_get_image_editor('image.jpg');
exact($image, array(200, 200, true));
$image->stream();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment