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;">&nbsp;</div> Gives me: <div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div> How can I do both? Resize the image and then cut it the size I want?


当前回答

<p class="crop"><a href="http://templatica.com" title="Css Templates">
    <img src="img.jpg" alt="css template" /></a></p> 

.crop {
    float: left;
    margin: .5em 10px .5em 0;
    overflow: hidden; /* this is important */
    position: relative; /* this is important too */
    border: 1px solid #ccc;
    width: 150px;
    height: 90px;
}
.crop img {
    position: absolute;
    top: -20px;
    left: -55px;
}

其他回答

.imgContainer {
  overflow: hidden;
  width: 200px;
  height: 100px;
}
.imgContainer img {
  width: 200px;
  height: 120px;
}
<div class="imgContainer">
  <img src="imageSrc" />
</div>

包含的div本质上是通过隐藏溢出来裁剪图像。

使用CSS3,可以通过background-size来改变背景图像的大小,同时实现这两个目标。

在css3.info上有很多例子。

基于您的示例实现,使用donald_duck_4.jpg。在本例中,background-size: cover;正是你想要的-它适合背景图像覆盖整个区域的包含<div>和剪辑多余的部分(取决于比例)。

.with-bg-size { 背景图片:url (https://i.stack.imgur.com/wPh0S.jpg); 宽度:200 px; 身高:100 px; 背景位置:中心; /*使背景图像覆盖<div>的区域,并剪辑多余的*/ background-size:封面; } <div class="with-bg-size">唐老鸭!< / div >

Css3 background-image background-size

<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*/
}

尝试使用clip-path属性:

剪切路径属性允许您将元素剪切为基本形状或 SVG源代码。 注意:clip-path属性将替换已弃用的剪辑 财产。

img { 宽度:150 px; 剪辑路径:插入(30px 35px); } < img src = " http://i.stack.imgur.com/wPh0S.jpg " >

这里有更多的例子。

你可以使用Kodem的图片调整服务。您可以通过http调用调整任何图像的大小。可以在浏览器中随意使用,也可以在生产应用程序中使用。

上传图片到你喜欢的地方(S3, imgur等) 将其插入到您的专用API url(从我们的仪表板)