Ale*_*lan 11 php algorithm resize image aspect-ratio
我正在为iPhone应用程序创建一个Web服务来进行交互.
当我的客户端上传服务器端的图像时,我希望我的php脚本调整图像大小,同时保持纵横比,以便它适合iPhone屏幕.(即最长边<= 960,最短<= 640
我在JS中创建了一个模型,只是因为我发现它更容易快速完成.
我很确定,虽然我可能错了,但这不是最有效的方法.有人可以用更好的逻辑(尤其是开头的那个)或更接近这个的数学方法来纠正我吗?
var w = 960, h = 960, new_w, new_h;
if (w >= h && w > 960 || h >= w && h > 960 || w >= h && h > 640 || h >= w && w > 640) {
if (w > h) {
if (w>960) {
new_w = 960;
new_h = h*(new_w/w);
}
if (h>640) {
new_h = 640;
new_w = w*(new_h/h);
}
}
else {
if (h>960) {
new_h = 960;
new_w = w*(new_h/h);
}
if (w>640) {
new_w = 640;
new_h = h*(new_w/w);
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 41
也许稍微短一点的例程是:
// Calculate resize ratios for resizing
float ratioW = targetWidth / oldWidth;
float ratioH = targetHeight / oldHeight;
// smaller ratio will ensure that the image fits in the view
float ratio = ratioW < ratioH?ratioW:ratioH;
newWidth = oldWidth*ratio;
newHeight = oldHeight*ratio;
Run Code Online (Sandbox Code Playgroud)
显然,如果比率> 1,那么它正在扩大,如果<1那么它正在缩小.
Jim*_*hel 24
我认为以下内容应该给你这个想法.它不是任何特定的语言,而是类似C的伪代码.
shortSideMax = 640;
longSideMax = 960;
function Resize(image)
{
if (image.width >= image.height)
{
if (image.width <= longSideMax && image.height <= shortSideMax)
return image; // no resizing required
wRatio = longSideMax / image.width;
hRatio = shortSideMax / image.height;
}
else
{
if (image.height <= longSideMax && image.width <= shortSideMax)
return image; // no resizing required
wRatio = shortSideMax / image.width;
hRatio = longSideMax / image.height;
}
// hRatio and wRatio now have the scaling factors for height and width.
// You want the smallest of the two to ensure that the resulting image
// fits in the desired frame and maintains the aspect ratio.
resizeRatio = Min(wRatio, hRatio);
newHeight = image.Height * resizeRatio;
newWidth = image.Width * resizeRatio;
// Now call function to resize original image to [newWidth, newHeight]
// and return the result.
}
Run Code Online (Sandbox Code Playgroud)
此代码的效率或您拥有的代码不会成为问题.实际调整图像大小所需的时间将使进行几次比较,两次除法和两次乘法所花费的时间相形见绌.
这是一种"更加数学化"的方式吗?我想,因为它将你的四个案件分成两个.但方法基本相同.
小智 7
下面,我知道保持比例的最简单方法.希望能帮助到你.
使用Javascript
function resize(width, height, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / width, maxHeight / height);
var newWidth = ratio * width;
var newHeight = ratio * height;
console.log(newWidth + ' ' + newHeight); // Test
// Process resizing...
}
resize(1280, 1024, 600, 300);
Run Code Online (Sandbox Code Playgroud)
PHP
function resize($width, $height, $maxWidth, $maxHeight) {
$ratio = min(array($maxWidth / $width, $maxHeight / $height));
$newWidth = $ratio * $width;
$newHeight = $ratio * $height;
echo $newWidth . ' ' . $newHeight; // Test
// Process resizing...
}
resize(1600, 1280, 150, 150);
Run Code Online (Sandbox Code Playgroud)