WordPress原生动态裁剪图像

由于WordPress会自动生成多种尺寸的图像,对服务器空间占用浪费。有多个版本可以动态调整图像尺寸。
有几个脚本来调整在运行诸如Aqua Resizer, vt_resizer, script by Konstantin Kovshenin, Dynamic Image Resizer。他们很棒,工作得很好。
但对我来说似乎很重要。我想要的只是一个脚本,它调整了一个由附件ID(而不是URL)传递的图像,下面贴上代码。


function rw_image_resize( $attachment_id, $width, $height, $crop = true )
{
$path = get_attached_file( $attachment_id );
if ( ! file_exists( $path ) )
{
return false;
}
$upload = wp_upload_dir();
$path_info = pathinfo( $path );
$base_url = $upload['baseurl'] . str_replace( $upload['basedir'], '', $path_info['dirname'] );
$meta = wp_get_attachment_metadata( $attachment_id );
foreach ( $meta['sizes'] as $key => $size )
{
if ( $size['width'] == $width && $size['height'] == $height )
{
return "{$base_url}/{$size['file']}";
}
}
// Generate new size
$resized = image_make_intermediate_size( $path, $width, $height, $crop );
if ( $resized && ! is_wp_error( $resized ) )
{
// Let metadata know about our new size.
$key = sprintf( 'resized-%dx%d', $width, $height );
$meta['sizes'][$key] = $resized;
wp_update_attachment_metadata( $attachment_id, $meta );
return "{$base_url}/{$resized['file']}";
}
// Return original if fails
return "{$base_url}/{$path_info['basename']}";
}