我正在处理图像,我遇到了纵横比问题。
<img src="big_image.jpg" width="900" height="600" alt="" />
如您所见,高度和宽度已经指定。我为图像添加了CSS规则:
img {
max-width: 500px;
}
但对于big_image.jpg,我得到的宽度=500,高度=600。如何设置图像的大小,同时保持其纵横比。
我正在处理图像,我遇到了纵横比问题。
<img src="big_image.jpg" width="900" height="600" alt="" />
如您所见,高度和宽度已经指定。我为图像添加了CSS规则:
img {
max-width: 500px;
}
但对于big_image.jpg,我得到的宽度=500,高度=600。如何设置图像的大小,同时保持其纵横比。
当前回答
要强制图像符合精确的大小,您不需要编写太多代码。太简单了
国际货币基金组织{宽度:200px;高度:自动;对象拟合:包含;/*按图像大小调整徽标*/-o-object-fit:contain;/*为opera浏览器安装徽标*/对象位置:顶部;/*设置徽标位置*/-o对象位置:顶部;/*opera浏览器的徽标位置*/}<img src=“http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png“alt=”徽标“>
其他回答
如果图像对于指定区域太大,这将使图像收缩(作为缺点,它不会放大图像)。
setec的解决方案适用于自动模式下的“收缩到适合”。但是,为了最佳地扩展以适应“自动”模式,您需要首先将接收到的图像放入临时id,检查它是否可以在高度或宽度上扩展(取决于其纵横比v/s,即显示块的纵横比),
$(".temp_image").attr("src","str.jpg" ).load(function() {
// callback to get actual size of received image
// define to expand image in Height
if(($(".temp_image").height() / $(".temp_image").width()) > display_aspect_ratio ) {
$(".image").css('height', max_height_of_box);
$(".image").css('width',' auto');
} else {
// define to expand image in Width
$(".image").css('width' ,max_width_of_box);
$(".image").css('height','auto');
}
//Finally put the image to Completely Fill the display area while maintaining aspect ratio.
$(".image").attr("src","str.jpg");
});
当接收到的图像小于显示框时,这种方法很有用。您必须将它们保存在服务器上的原始小尺寸,而不是其扩展版本,以填充更大的显示框,以节省大小和带宽。
要保持响应图像,同时仍然强制图像具有一定的纵横比,可以执行以下操作:
HTML格式:
<div class="ratio2-1">
<img src="../image.png" alt="image">
</div>
和SCSS:
.ratio2-1 {
overflow: hidden;
position: relative;
&:before {
content: '';
display: block;
padding-top: 50%; // ratio 2:1
}
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
}
无论作者上传的图像大小如何,这都可以用于强制执行特定的纵横比。
感谢@Ksesohttp://codepen.io/Kseso/pen/bfdhg.查看此URL以了解更多比率和工作示例。
您可以创建如下div:
<div class="image" style="background-image:url('/to/your/image')"></div>
并使用此css设置其样式:
height: 100%;
width: 100%;
background-position: center center;
background-repeat: no-repeat;
background-size: contain; // this can also be cover
如果应用程序可以具有任何纵横比或分辨率的图像,则可以像此链接中那样管理高度和宽度。
这使用Javascript和HTML
https://stackoverflow.com/a/65090175/13338731
删除“height”属性。
<img src="big_image.jpg" width="900" alt=""/>
通过指定这两个选项,可以更改图像的纵横比。只需设置一个即可调整大小,但保持纵横比。
(可选)限制过大:
<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>