I want to show an image from an URL with a certain width and height even if it has a different size ratio. So I want to resize (maintaining the ratio) and then cut the image to the size I want. I can resize with html img property and I can cut with background-image. How can I do both? Example: This image: Has the size 800x600 pixels and I want to show like an image of 200x100 pixels With img I can resize the image 200x150px: <img style="width: 200px; height: 150px;" src="http://i.stack.imgur.com/wPh0S.jpg"> That gives me this: <img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg"> And with background-image I can cut the image 200x100 pixels. <div style="background-image: url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div> Gives me: <div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div> How can I do both? Resize the image and then cut it the size I want?
当前回答
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
包含的div本质上是通过隐藏溢出来裁剪图像。
其他回答
有像Filestack这样的服务可以帮你做这件事。
它们获取你的图像url,并允许你使用url参数来调整它的大小。这很简单。
将图像大小调整为200x100,但保持纵横比后,图像将如下所示
整个url看起来像这样
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
但重要的是
resize=width:200/crop=d:[0,25,200,100]
<div class="crop">
<img src="image.jpg"/>
</div>
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 100%;
/*Here you can use margins for accurate positioning of cropped image*/
}
在之前的答案中增加了一个小的内容,包括对象合身:封面:
对象的位置
您可以使用object-position属性更改替换元素的内容对象在元素框中的对齐方式。
.trimmed-cover { object-fit:封面; 宽度:100%; 身高:177 px; 物体位置:中心40%; } <img class="trim -cover" src="http://i.stack.imgur.com/wPh0S.jpg">
尝试使用clip-path属性:
剪切路径属性允许您将元素剪切为基本形状或 SVG源代码。 注意:clip-path属性将替换已弃用的剪辑 财产。
img { 宽度:150 px; 剪辑路径:插入(30px 35px); } < img src = " http://i.stack.imgur.com/wPh0S.jpg " >
这里有更多的例子。
我所做的是创建一个服务器端脚本,它将在服务器端调整大小和裁剪图片,这样它就会在互联网上发送更少的数据。
它相当简单,但如果有人感兴趣,我可以挖掘并发布代码(asp.net)