let*_*ngo 13 php image-resizing
我在我正在处理的网站上有一个区域,它将显示从外部源提取的用户个人资料图像(因此无法控制其原始大小).
我要做的是拍摄一张图片(在这个例子中1000px x 800px并将其调整为200px x 150px.显然,这有一个宽高比差异.
我想要做的是调整原始图像的大小而不失真,在这种情况下会产生200px x 160px图像.我当时想做的是从边缘裁剪任何多余的部分以产生正确的图像尺寸.因此,在这种情况下裁剪5px图像的顶部和底部,最终产生一个200px x 150px.
我目前有WideImage库,并希望使用它.我在SO上看过几个类似的问题,但我没想到的就是我想要实现的目标.
bin*_*yLV 27
你可以试试:
$img->resize(200, 150, 'outside')->crop('center', 'middle', 200, 150);
Run Code Online (Sandbox Code Playgroud)
有些用户发布他们的计算版本......这也是我的版本:
$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);
Run Code Online (Sandbox Code Playgroud)
小智 8
我尝试了所有的解决方案,每次都想出奇怪的数字.所以,这是我进行计算的方式.
基本比例公式:a/b = x/y - > ay = bx然后求解未知值.所以,让我们把它放到代码中.
此功能假定您已将图像打开为变量.如果你传递路径,你必须在函数中打开图像,做数学,杀死它,返回值,然后在你调整大小时再次打开图像,这是低效的...
function resize_values($image){
#for the purpose of this example, we'll set this here
#to make this function more powerful, i'd pass these
#to the function on the fly
$maxWidth = 200;
$maxHeight = 200;
#get the size of the image you're resizing.
$origHeight = imagesy($image);
$origWidth = imagesx($image);
#check for longest side, we'll be seeing that to the max value above
if($origHeight > $origWidth){ #if height is more than width
$newWidth = ($maxHeight * $origWidth) / $origHeight;
$retval = array(width => $newWidth, height => $maxHeight);
}else{
$newHeight= ($maxWidth * $origHeight) / $origWidth;
$retval = array(width => $maxWidth, height => $newHeight);
}
return $retval;
}
Run Code Online (Sandbox Code Playgroud)
上面的函数显然返回一个数组.您可以将公式运行到您正在处理的任何脚本中.事实证明这是适合这项工作的公式.所以......取决于你是否使用它.后来!
| 归档时间: |
|
| 查看次数: |
25231 次 |
| 最近记录: |