我正在尝试使用 php 在我的 wordpress 插件中调整图像大小,但它们不起作用。如何使用 php 将图像大小调整为
正确?有人知道这是否可能吗?
谢谢
您可以使用WordPress内置的大小调整功能:
<?php image_resize( $file, $max_w, $max_h, $crop, $suffix, $dest_path, $jpeg_quality ); ?>
您可以在此处找到更多详细信息:http://codex.wordpress.org/Function_Reference/image_resize
此函数将 imagePath 作为参数以及您希望它调整图像大小的大小。这将使用比例约束调整图像大小
假设大小 = 300那么会有三种情况
1)如果图像的高度大于宽度,则其高度将为300
2)如果宽度较大,则其宽度将为300
3)如果图像的比例为1:1,则其高度和宽度都将为300
function resizeImage($imagePath,$size)
{
$sizeData = getimagesize($imagePath);
$width = $sizeData[0];
$height = $sizeData[1];
# Loading image to memory according to type
switch ( $sizeData[2] ) {
case IMAGETYPE_GIF: $src = imagecreatefromgif($imagePath); break;
case IMAGETYPE_JPEG: $src = imagecreatefromjpeg($imagePath); break;
case IMAGETYPE_PNG: $src = imagecreatefrompng($imagePath); break;
default: return false;
}
if(!$src)
{
return false;
}
if($height >= $width)
{
$newheight = $size;
$newwidth = ($newheight*$width)/$height;
}
else
{
$newwidth = $size;
$newheight = ($height/$width)*$newwidth;
}
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
# Writing image according to type to the output destination
switch ( $sizeData[2] ) {
case IMAGETYPE_GIF: imagegif($tmp, $imagePath); break;
case IMAGETYPE_JPEG: imagejpeg($tmp, $imagePath, 100); break;
case IMAGETYPE_PNG: imagepng($tmp, $imagePath, 9); break;
default: return false;
}
imagedestroy($src);
imagedestroy($tmp);
return true;
}