调整图像大小而不会变形,保持宽高比,然后使用WideImage裁切多余的图像 [英] Resize image without distortion keeping aspect ratio then crop excess using WideImage
问题描述
我正在工作的站点上有一个区域,该区域将显示从外部来源提取的用户个人资料图像(因此无法控制其原始大小).
I have an area on a site that I am working on that will display a users profile image that is pulled from an external source (therefore no control on its original size).
我想要做的是拍摄一张图像(在本例中为1000px x 800px
并将其调整为200px x 150px
.显然,这存在长宽比差异.
What I am looking to do is take an image (in this example 1000px x 800px
and resize it to 200px x 150px
. Obviously with this there is an aspect ratio difference.
我想做的是调整原始图像的大小,而不会失真,在这种情况下会产生一个200px x 160px
图像.然后,我想做的是从边缘裁剪掉多余的部分,以产生正确的图像尺寸.因此,在这种情况下,裁剪图像顶部和底部的5px
最终会产生200px x 150px
.
What I want to do is resize the original image without distortion, which in this case would produce a 200px x 160px
image. What I then want to do is crop any excess from the edges to produce the correct image size. So in this case crop 5px
off the top and bottom of the image finally producing a 200px x 150px
.
我目前拥有 WideImage 库,并希望使用该库.我已经在SO上看到了几个类似的问题,但是我无法说出我想要达到的目标.
I have the WideImage library currently and would like to use that. I have seen several similar questions on SO but nothing that I can say exactly does as I am trying to achieve.
推荐答案
您可以尝试:
$img->resize(200, 150, 'outside')->crop('center', 'middle', 200, 150);
一些用户发布他们的计算版本...这也是我的版本:
Some users post their versions of calculations... Here's also my version:
$sourceWidth = 1000;
$sourceHeight = 250;
$targetWidth = 200;
$targetHeight = 150;
$sourceRatio = $sourceWidth / $sourceHeight;
$targetRatio = $targetWidth / $targetHeight;
if ( $sourceRatio < $targetRatio ) {
$scale = $sourceWidth / $targetWidth;
} else {
$scale = $sourceHeight / $targetHeight;
}
$resizeWidth = (int)($sourceWidth / $scale);
$resizeHeight = (int)($sourceHeight / $scale);
$cropLeft = (int)(($resizeWidth - $targetWidth) / 2);
$cropTop = (int)(($resizeHeight - $targetHeight) / 2);
var_dump($resizeWidth, $resizeHeight, $cropLeft, $cropTop);
这篇关于调整图像大小而不会变形,保持宽高比,然后使用WideImage裁切多余的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!