调整图像大小并保持纵横比以适合 iPhone 的算法 [英] Algorithm to resize image and maintain aspect ratio to fit iPhone
问题描述
我正在为 iPhone 应用创建一个网络服务来与之交互.
I'm creating a web service for an iPhone app to interact with.
当我的客户端在服务器端上传图像时,我希望我的 php 脚本调整图像大小,同时保持纵横比,使其适合 iPhone 屏幕.(即最长边 <= 960,最短边 <= 640
When my client uploads images server-side, I want my php script to resize the image, whilst maintaining the aspect ratio, so that it will fit onto the iPhone screen. (i.e. the longest side is <= 960 and the shortest <= 640
我用 JS 创建了一个模型,只是因为我发现它更容易快速完成.
I've created a mock-up in JS, simply because I find it easier to do quickly.
我很确定,虽然我可能错了,但这不是最有效的方法.有人可以用更好的逻辑(尤其是开始时的那一点)或更数学的方法来纠正我吗?
I'm pretty sure, though I may be wrong, that this isn't the most efficient way of doing it. Could someone correct me with either better logic (especially the bit at the start), or a more mathematical way of approaching this?
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 的伪代码.
I think the following should give you the idea. It's not in any particular language, but rather a C-like pseudo code.
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.
}
这段代码的效率,或者你所拥有的,都不是问题.实际调整图像大小所需的时间比进行几次比较、两次除法和两次乘法所需的时间相形见绌.
The efficiency of this code, or what you have, won't be an issue. The time it takes to actually resize the image will dwarf the time it takes to do a couple of comparisons, two divides, and two multiplies.
这是一种更数学化"的方法吗?我想,因为它将您的四个案例折叠为两个.但方法本质上是一样的.
Is this a "more mathematical" way to do it? I suppose, in that it collapses your four cases into two. But the approach is essentially the same.
这篇关于调整图像大小并保持纵横比以适合 iPhone 的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!