我设法找到了问题的解决方案,尽管我最终使用了PHP GD函数而不是wordpress函数。我希望这能帮助其他试图做类似事情的人。
$src = // Source image URL
$max_w = // Output maximum width
$max_h = // Output maximum height
$dir = // Output directory
$fle = // Output filename
function createThumbnail( $src, $max_w, $max_h, $dir, $fle ) {
$img_url = file_get_contents( $src );
$img = imagecreatefromstring( $img_url );
$old_x = imagesx( $img ); // Source image width
$old_y = imagesy( $img ); // Source image height
// Conditions for maintaining output aspect ratio
switch ( true ) {
case ( $old_x > $old_y ): // If source image is in landscape orientation
$thumb_w = $max_w;
$thumb_h = $old_y / $old_x * $max_w;
break;
case ( $old_x < $old_y ): // If source image is in portrait orientation
$thumb_w = $old_x / $old_y * $max_h;
$thumb_h = $max_h;
break;
case ( $old_x == $old_y ): // If source image is a square
$thumb_w = $max_w;
$thumb_h = $max_h;
break;
}
$thumb = imagecreatetruecolor( $thumb_w, $thumb_h );
/**
I quoted this one out since I ran in compatibility issues, I\'m using PHP 5.3.x
and imagesetinterpolation() doesn\'t exist in this version
imagesetinterpolation( $thumb, IMG_SINC ); // Recommended Downsizing Algorithm
**/
imagecopyresampled( $thumb, $img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y );
$result = imagejpeg( $thumb, $dir . $fle );
imagedestroy( $thumb );
imagedestroy( $img );
return $result;
}