【发布时间】:2020-07-15 14:30:15
【问题描述】:
我已经建立了一个自定义 wordpress 网站并添加了一些自定义图像尺寸。
问题是当用户上传较小的图像 (700x300) 时。 比图像不会裁剪以适应自定义纵横比。
如何放大图像以适合我的裁剪尺寸(1:1 宽高比)?
这是我的裁剪功能:
add_image_size( 'article-crop', 700, 700, true );
【问题讨论】:
我已经建立了一个自定义 wordpress 网站并添加了一些自定义图像尺寸。
问题是当用户上传较小的图像 (700x300) 时。 比图像不会裁剪以适应自定义纵横比。
如何放大图像以适合我的裁剪尺寸(1:1 宽高比)?
这是我的裁剪功能:
add_image_size( 'article-crop', 700, 700, true );
【问题讨论】:
可以通过将此代码添加到主题的 functions.php 文件来修复它。它会放大图像以适合所有缩略图大小并正确裁剪它们。
/* Thumbnail upscale
/* ------------------------------------ */
function alx_thumbnail_upscale( $default, $orig_w, $orig_h, $new_w, $new_h, $crop ){
if ( !$crop ) return null; // let the wordpress default function handle this
$aspect_ratio = $orig_w / $orig_h;
$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
$crop_w = round($new_w / $size_ratio);
$crop_h = round($new_h / $size_ratio);
$s_x = floor( ($orig_w - $crop_w) / 2 );
$s_y = floor( ($orig_h - $crop_h) / 2 );
return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
}
add_filter( 'image_resize_dimensions', 'alx_thumbnail_upscale', 10, 6 );
【讨论】:
$size_ratio = ... 之后添加此 if ($aspect_ratio > 1) { if ($orig_w < $new_w) return null; if ($orig_h < $new_w) return false; } elseif ($aspect_ratio < 1) { if ($orig_h < $new_h) return null; if ($orig_w < $new_h) return false; } else { return null; }。