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?


当前回答

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

其他回答

生活例子: https://jsfiddle.net/de4Lt57z/

HTML:

<div class="crop">
  <img src="example.jpg" alt="..." />
</div>

CSS:

    .crop img{
      width:400px;
      height:300px;
      position: absolute;
      clip: rect(0px,200px, 150px, 0px);
      }

解释: 在这里,图像是根据图像的宽度和高度值调整大小。裁剪是通过剪辑属性完成的。

有关剪辑属性的详细信息请参见: http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/

你试过用这个吗?

.centered-and-cropped { object-fit: cover }

我需要调整图像的大小,中心(垂直和水平),然后裁剪它。

我很高兴地发现,它可以在一个css行中完成。 在这里查看示例:http://codepen.io/chrisnager/pen/azWWgr/?editors=110


下面是这个例子的CSS和HTMLcode:

.居中剪裁{对象合身:封面} <标题>原始h1 > < / <img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="熊"> <标题> object-fit:封面h1 > < / <img class="center -and-裁剪" width="200" height="200" style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="熊">

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

有像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]

谢谢sanchothefat。

我对你的回答有改进的地方。由于裁剪是非常适合每一个图像,这个定义应该在HTML而不是CSS。

<div style="overflow:hidden;">
   <img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>