我正在尝试完成此功能,除了 1 个小问题外,它似乎工作得很好 - 它似乎将图像定位得太靠左,然后用黑色填充其余空间。
我想要做的是获取此函数以将图像调整为指定的 $thumb_w,如果调整后高度最终大于 $thumb_h,它只会裁剪掉底部。
这是我的函数代码:
function resize_upload ($tmp, $thumb_w, $thumb_h, $img_name, $img_ext, $img_path)
{
if ($img_ext == 'jpg' || $img_ext == 'jpeg' || $img_ext == 'png' || $img_ext == 'gif')
{
if ($img_ext == 'jpg' || $img_ext == 'jpeg')
$source_img = imagecreatefromjpeg($tmp);
else if ($img_ext=='png')
$source_img = imagecreatefrompng($tmp);
else
$source_img = imagecreatefromgif($tmp);
$orig_w = imagesx($source_img);
$orig_h = imagesy($source_img);
$w_ratio = ($thumb_w / $orig_w);
$h_ratio = ($thumb_h / $orig_h);
if ($orig_w > $orig_h )
{
$crop_w = round($orig_w * $h_ratio);
$crop_h = $thumb_h;
$src_x = ceil( ( $orig_w - $thumb_w ) / 2 );
$src_y = 0;
}
elseif ($orig_w < $orig_h )
{
$crop_h = round($orig_h * $w_ratio);
$crop_w = $thumb_w;
$src_x = 0;
$src_y = ceil( ( $orig_h - $thumb_h ) / 2 );
}
else
{
$crop_w = $thumb_w;
$crop_h = $thumb_h;
$src_x = 0;
$src_y = 0;
}
$thumb_img = imagecreatetruecolor($thumb_w,$thumb_h);
imagecopyresampled($thumb_img, $source_img, 0 , 0 , $src_x, $src_y, $crop_w, $crop_h, $orig_w, $orig_h);
imagejpeg($thumb_img, $img_path.'/'.$img_name.'.'.$img_ext, 100);
imagedestroy($thumb_img);
imagedestroy($source_img);
}
}
我是这样调用函数的:
resize_upload ($_FILES['image_main']['tmp_name'], 556, 346, $img_name, $img_ext, '../wp-content/themes/my-theme/images/projects');
这是函数执行完操作后图像的最终样子:
看到右边的黑色了吗?它可能是一些我无法弄清楚的数学问题。任何帮助将不胜感激。
最佳答案
使用您的帖子 $thumb_w = 556, $thumb_h = 346
中的相同变量,我们假设发送的图像尺寸完全相同,因此不需要调整大小( 556x346)。
$orig_w = 556;
$orig_h = 346;
$w_ratio = 1;
$h_ratio = 1;
if (556 > 346) //true
{
$crop_w = round(556 * 1); // 556
$crop_h = 346;
$src_x = ceil( ( 556 - 346 ) / 2 ); // ceil( 210 / 2 ) == 105;
$src_y = 0;
}
...
$thumb_img = imagecreatetruecolor(556, 346);
imagecopyresampled($thumb_img, $source_img, 0, 0, 105, 0, 556, 346, 556, 346);
因此,您的代码从源图像的 x = 105
开始,并尝试向右移动 556 像素,但超过该点后仅存在 451 像素。因此,如果我发送了一张 556x346 的图像,它会为图像的水平部分复制 105 到 556 像素的宽度,然后为垂直部分复制 0 到 346 的像素宽度。因此,会显示图像的整个垂直部分,但不会显示整个宽度。
我敢肯定,如果我们对高度大于宽度的图像进行这些相同的计算,我们会遇到同样的问题,因为图像底部有黑色空间。
提示:在编写公式和其他需要大量计算的东西时,请先用最简单的数字进行计算。如果这些都不起作用,那么您显然做错了什么。
关于php - 调整大小后的图像中有黑色方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8977086/