调整图像大小并保持宽高比以适合iPhone的算法
问题内容:
我正在创建一个与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);
}
}
}
问题答案:
我认为以下内容应该可以给您这个想法。它不是任何特定的语言,而是类似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.
}
这段代码的效率或您拥有的代码都不会成为问题。实际调整图像大小所需的时间将使进行两次比较,两次除法和两次乘法所需的时间相形见war。
这是“更数学”的方法吗?我想是因为它会将您的四个案例分解为两个。但是方法本质上是相同的。