简体   繁体   中英

How do I force a WP_Image_Editor.resize to stretch my image if needed?

When I call the function WP_Image_Editor->resize(...) and the image's height is too small, it ignores the height I pass in. For example:

//This image is 300 x 225
$image = wp_get_image_editor( "/var/www/wp-content/uploads/2014/03/test.jpg" );

//I tell it to resize to 290 x 290
$image->resize( 290, 290 ); //Passing "true" to crop doesn't help)

//It saves, but as 290 x 225!
$image->save( "/var/www/wp-content/uploads/2014/03/test-22.jpg" );

How do I make it stretch to the proper size and ratio?

EDIT Here is what's returned by each function call above:

//var_dump of wp_get_image_editor( $myImagePath );
object(WP_Image_Editor_Imagick)#109 (6) {
    ["image":protected]=>
    object(Imagick)#108 (0) {
    }
    ["file":protected]=>
    string(65) "/var/www/wp-content/uploads/2014/03/test.jpg"
    ["size":protected]=>
    array(2) {
        ["width"]=>
        int(300)
        ["height"]=>
        int(225)
    }
    ["mime_type":protected]=>
    string(10) "image/jpeg"
    ["default_mime_type":protected]=>
    string(10) "image/jpeg"
    ["quality":protected]=>
    int(90)
}

//var_dump of $image->resize( 290, 290 );
bool(true)

//var_dump of $image->save( "/var/www/wp-content/uploads/2014/03/test-22.jpg" );
array(5) {
    ["path"]=>
    string(68) "/var/www/wp-content/uploads/2014/03/test-22.jpg"
    ["file"]=>
    string(11) "test-22.jpg"
    ["width"]=>
    int(294)
    ["height"]=>
    int(225)
    ["mime-type"]=>
    string(10) "image/jpeg"
}

Try adding a filename into your $image->save(); call.

If you refer to the docs [1] you can see they pass in a new filename.

[1] http://codex.wordpress.org/Function_Reference/wp_get_image_editor

WordPress has a built-in limit that comes from the image_resize_dimensions function (in wp-includes/media.php).

// Stop if the destination size is larger than the original image dimensions.

There's a filter, though, called image_resize_dimensions which you can use like so:

add_filter( 'image_resize_dimensions', function( $output, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) {
    return array( 0, 0, 0, 0, $dest_w, $dest_h, $orig_w, $orig_h );
}, 10, 6 );

The above will ignore aspect ratios and whatnot and just return what you asked for and results in stretched images. Be careful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM