【发布时间】:2016-04-04 06:38:46
【问题描述】:
我在functions.php中添加了add_image_size,当图像足够大时它会调整图像大小,但是当图像小于大小时它不会调整图像大小。
例如,我添加了add_image_size( 'category', 255, 150, true );。
但是用户上传了一些大小为150x150的图片,它不够大。
这是我在图像小于我需要的尺寸时调整图像大小的代码:
if ( !function_exists( 'mit_resize') ) {
function mit_resize( $attachment, $width, $height, $url = false, $crop = true ) {
$siteurl = get_option( 'siteurl' );
if ( $url === false ) {
$file_path = get_attached_file( $attachment );
} else if ( $attachment ) {
$file_path = get_attached_file(mit_get_attachment_id($attachment));
}
if ( empty($file_path) )
return false;
$file_info = pathinfo( $file_path );
$extension = '.'. $file_info['extension'];
$base_file = $file_info['dirname'].'/'.$file_info['filename'].$extension;
$sizes = mit_get_image_sizes();
$general = getimagesize($base_file);
foreach ($sizes as $key => $size) {
if($size['width'] == $width && $size['height'] == $height && $general[0] >= $size['width'] && $general[1] >= $size['height']) {
$path = explode('wp-content',$file_info['dirname'].'/'.$file_info['filename'].'-'.$width.'x'.$height.$extension);
return $siteurl . '/wp-content' . $path[1];
}
}
if (file_exists($base_file))
{
$no_ext_path = $file_info['dirname'].'/'.$file_info['filename'];
$img_resize = wp_get_image_editor( $no_ext_path.$extension);
if ( ! is_wp_error( $img_resize ) ) {
$cropped_img_path = $no_ext_path.'-'.$width.'x'.$height.$extension;
$img_resize->resize( $width, $height, $crop );
$img_resize->save($cropped_img_path);
if (preg_match("/wp-content/", $cropped_img_path) != false) {
$path = explode('wp-content',$cropped_img_path);
}
else
return 'http://placehold.it/' . $width .'x' . $height . '?text=Img';
$url_file = $siteurl . '/wp-content' .$path[1];
}
}
if ( !file_exists($cropped_img_path) )
{
return 'http://placehold.it/' . $width .'x' . $height . '?text=Img';
}
else
return $url_file;
}
}
我可以将此函数与 add_image_size 挂钩吗?
【问题讨论】:
-
这是不可能的。您可以为上传分钟设置 valition。尺寸
标签: wordpress