缩放图像完全填充边框
问题描述:
举例来说,如果我需要填一个边框是100像素宽50像素高,下面的输入图像会有以下行为:缩放图像完全填充边框
200瓦特X 200H得到缩小50%和 25%被砍掉顶部和 底部。
200w x 100h得到缩小50% 没有裁剪。
100w x 200h获得不缩放,但是012px75px被砍掉顶部和底部。
这似乎是一个常见的调整大小功能,但我一直无法找到算法的一个例子。
接受包括伪代码在内的任何语言的答案。带有答案的页面链接也很棒!
答
你要的东西很简单。计算宽度和高度的不同比例因子,然后从实际比例因子中选取较大的比例因子。将您的输入尺寸乘以比例,并裁剪出来的尺寸太大。
scale = max(maxwidth/oldwidth, maxheight/oldheight)
scaledwidth = oldwidth * scale
scaledheight = oldheight * scale
if scaledheight > maxheight:
croptop = (scaledheight - maxheight)/2
cropbottom = (scaledheight - maxheight) - croptop
if scaledwidth > maxwidth:
cropleft = (scaledwidth - maxwidth)/2
cropright = (scaledwidth - maxwidth) - cropleft
答
在这里,我们确保我们只在X大于100%时才缩放;那么在我们完成之后,我们确保我们在Y上只有50 px。如果我们大于50,那么我们取差值并除以2得到从顶部/底部移除的量。
double percent_x = 1.0;
if(X > 100) {
percent_x = (float)100/X;
X *= percent_x;
Y *= percent_x;
}
int diff_y;
int top_cut, bott_cut;
if(Y > 50) {
diff_y = (Y - 50)/2;
top_cut = bott_cut = diff_y;
}
答
马克赎金的答案很大程度上鼓舞(非常感谢你 - 你救了我)。对于任何人谁愿意做这个没有裁剪图像(只适合范围内),我发现,这个工程:
if (maxWidth > width && maxHeight > height) {
return { width, height };
}
aspectRatio = width/height,
scale = max(maxWidth/width, maxHeight/height);
scaledHeight = height * scale,
scaledWidth = width * scale;
if (scaledHeight > maxHeight) {
scaledHeight = maxHeight;
scaledWidth = aspectRatio * scaledHeight;
} else if (scaledWidth > maxWidth) {
scaledWidth = maxWidth;
scaledHeight = scaledWidth/aspectRatio;
}
return { scaledHeight, scaledWidth };
有人留在我的答案评论,我以为是你,但它不是 - 你能澄清一下关于你的实际限制的问题吗?谢谢。 – 2009-03-06 04:46:01
一般情况是我想要的。谢谢。 – Larsenal 2009-03-06 05:25:33