我该如何在jQuery中调整图像大小以保持一致的长宽比?例如设置最大高度并使宽度正确调整。谢谢。
我该如何在jQuery中调整图像大小以保持一致的长宽比?例如设置最大高度并使宽度正确调整。谢谢。
这是一个可能会做你想要的事情的有用函数:
jQuery.fn.fitToParent = function()
{
this.each(function()
{
var width = $(this).width();
var height = $(this).height();
var parentWidth = $(this).parent().width();
var parentHeight = $(this).parent().height();
if(width/parentWidth < height/parentHeight) {
newWidth = parentWidth;
newHeight = newWidth/width*height;
}
else {
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
var margin_top = (parentHeight - newHeight) / 2;
var margin_left = (parentWidth - newWidth ) / 2;
$(this).css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
});
};
基本上,它会抓取一个元素,将其居中放置在父级内,然后拉伸其大小以适应整个父级,使得父级的背景不可见,同时保持其宽高比。
但是,这也可能不是您想要做的事情。
function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}
请确保使用原始的图像值,否则它会随着时间的推移而降低质量。
编辑:示例jQuery版本(未经测试)
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
var aspectRatio = $(this).data('aspectRatio');
if (aspectRatio == undefined) {
aspectRatio = $(this).width() / $(this).height();
$(this).data('aspectRatio', aspectRatio);
}
$(this).height(newHeight);
$(this).width(parseInt(newHeight * aspectRatio));
}
$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });
aspectRatio: true -> 保持原始宽高比
哎呀,这个世界上有太多的复制粘贴者了!我也想知道这个问题,但我看到的都是无尽的缩放宽度或高度的例子...谁会想要另一个溢出呢?!
应该很容易转换成JavaScript或其他语言。
//////////////
private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
double srcWidth = img.Width;
double srcHeight = img.Height;
double resizeWidth = srcWidth;
double resizeHeight = srcHeight;
double aspect = resizeWidth / resizeHeight;
if (resizeWidth > maxWidth)
{
resizeWidth = maxWidth;
resizeHeight = resizeWidth / aspect;
}
if (resizeHeight > maxHeight)
{
aspect = resizeWidth / resizeHeight;
resizeHeight = maxHeight;
resizeWidth = resizeHeight * aspect;
}
img.Width = resizeWidth;
img.Height = resizeHeight;
}
如果您需要完美的高度和宽度比例,这是一个很好的解决方案。裁剪后它将给出完美的裁剪比例。
getPerfectRatio(img,widthRatio,heightRatio){
if(widthRatio < heightRatio){
var height = img.scalingHeight - (img.scalingHeight % heightRatio);
var finalHeight = height
var finalWidth = widthRatio * (height/heightRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
if(heightRatio < widthRatio){;
var width = img.scalingWidth - (img.scalingWidth % widthRatio);
var finalWidth = width;
var finalHeight = heightRatio * (width/widthRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
return img
}